render json data and partial view with single ajax request

自闭症网瘾萝莉.ら 提交于 2019-12-02 06:37:47

You cannot send text/html and application/json for a single request. You could send either one.

If you are returning PartialView from controller, then the content type will be set to text/html. But still you can render the JSON as part of partial view.

public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });
        ViewBag.Months=myMonths;
    return PartialView("MonthwiseFees");

}

Then in your partial view

<script>
var myJSArray=@Html.Raw(JSON.Encode(ViewBag.Months)
</script>

jQuery

success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(myJSArray, function(index, item) {
        //myJSArray will be available in window scope now
    })
}

Update: Based on updated question

Controller

public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });        
    return PartialView("MonthwiseFees",myMonths);

}

This will check all the check boxes as I pass true for Html.CheckBox. This needs to be determined with the model and months array

@model List<string>

@using System.Globalization;

@{

    Layout = null;
    string[] months =DateTimeFormatInfo.CurrentInfo.MonthNames;
    var countMonths=months.Count();
    int x = 1;
}
<div>

@for (int no=0;no<countMonths-1;no++)
{

    <tr>
        <td>
         @x
        </td>
        <td>
          @months[no]
        </td>
        <td>
            //determine true/false by comparing months and Model
            @Html.CheckBox(" " + @x, model.Contains(months[x]), new { @class="check",id="check"})           
         </td>
    </tr>
    x = x + 1;
}
</div>

jQuery

success: function(data) {
    $('#maindiv').html('');
    $('#maindiv').html(data);        
}
Yasser

Lets start with your following code

var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        });

Here I am assuming your myMonths gets filled with a list of integers. I suggest adding a .ToList(); to the above code. So now it becomes :

var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        }).ToList();

Now let's check your jquery code, your ajax's success method look like this

success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(data.myMonths, function(index, item) {
        //Here I want to access myMonths as Json
    })
}

Here you write $('#maindiv').html(data), data here is a collection of integers (collection of months), .html() wont work that way.

Now since you are using this ajax call to get the JSON values only. I don't see the need to return a Partial View for that. Your return statement from your action could look like :

return Json(myMonths, JsonRequestBehavior.AllowGet);

and now when you use the following jquery, you will be able to access each month as required:

$.each(data, function(index, item) {
    // here is your month in the 'item' variable.
    $('#maindiv').html(item)
})

Update 1:

I see you are trying to load your partial view using an ajax call and then also use the data returned in that ajax call.

Why dont you load your partial view using the @Html.Partial or @Html.Action (how to). And ideally that partial view should have a call to your action which return JSON data which then you could use accordingly.

Update 2:

Your latest comment says

One page load I don't need that view.I need that view on some button clicked.

This could be helpful : https://stackoverflow.com/a/11964905/1182982

Mir Gulam Sarwar

Thanks goes to Murali Murugesan and yasser for help

I used the concept of Murali Murugesan by sending necessary data the in ViewBag.But since my partial view is Not Strongly Typed ,for this reason I needed to use javascript.

I edited my controller Action like below

var months = fcDetailsService.GetStudentWiseCollectionDetail(foundStudent, sessionName, "01");
            var data = (from w in months
                        select new
                        {
                            w.Month

                        });
            ViewBag.Months = JsonConvert.SerializeObject(data);
            if (data != null)
            {
                return PartialView("MonthwiseFees", data);
            }
            else
                return Json("MonthwiseFees");

Then in my javascript, I did below

$(function () {
        var i = 0;
        var myarray = new Array();
        myarray =@Html.Raw(@ViewBag.Months)
            $('.check').each(function () {
                for (var x = 0; x < myarray.length; x++)
                {
                        var me = (JSON.stringify(myarray[x].Month))
                        if ($.trim(this.name) === $.trim(me)) {
                            $(this).prop("checked", true)
                            $(this).attr("disabled", true)
                            return true;
                    }
                }
            });
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!