Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

render json data and partial view with single ajax request

Code given below sends an ajax request to the controller.

 if (btid === '01') {
                var allData = {
                    "sessionName": $('#sessionname').val(),
                    "foundStudent": $('#studentId').val(),
                    "code":btid
                }
                var mySession = JSON.stringify(allData);
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("RenderView", "ManualFeesCollection")',
                    contentType: "application/json; charset=utf-8",
                    data: mySession,
                    success: function (data) {
                          $('#maindiv').html('')
                          $('#maindiv').html(data)
                          $.each(data.myMonths, function (index, item) {
                           //Here I want to access myMonths as Json
                        })
                    },
                })

Below in the Controller Action.

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

    }

But the problem is I am getting the view in the #maindiv,but not not getting

myMonths

as json, in the success function of ajax. I need to do something in view with those myMonths.Currently I am sending two ajax request(in the success of another) to accomplish.But I wish I could do it with a single ajax request.Thanks for spending time on my Issue.

Upvotes: 1

Views: 4676

Answers (3)

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

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 [email protected](@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;
                    }
                }
            });
    });

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

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 [email protected](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);        
}

Upvotes: 2

Yasser Shaikh
Yasser Shaikh

Reputation: 47804

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

Upvotes: 1

Related Questions