Robin Hames

Hints, tricks and tips relating to MS SQL Server and .NET
posts - 14 , comments - 45 , trackbacks - 0

Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

 

ASP.NET MVC3 provides out of the box support for binding a Json data object into a Model on postback. This maybe used with a JQuery Ajax function call to post selected data back to an action. It is also possible to return a partial view from the same action, and refresh this from the ajax success function. For example:

In my MVC3 Razor project, I create two model classes:

public class NameResponseModel
{
    public string Name { get; set; }
    public DateTime CurrentDateTime { get; set; }
    public IList<int> Numbers { get; set; }
}

public class UpdateNameModel
{
    public string Name { get; set; }
    public IEnumerable<int> Numbers { get; set; }
}

The UpdateNameModel will be used to retrieve data submitted by the Ajax method call. It is this model that the Json object will bind to. The NameResponseModel class is used to pass information back to the UI via a template view.

In the Views/Shared/DisplayTemplates folder, I created a template that is strongly typed to the NameResponseModel class, called NameResponseModel.cshtml:

@model MvcJQuery.Models.NameResponseModel

<div>
<div class="display-label">
    Name: @Html.DisplayFor(m => m.Name)
</div>
<div class="display-label">
    Current Date Time: @Html.DisplayFor(m => m.CurrentDateTime)
</div>
@{
    var numbersCount = Model.Numbers.Count;
   
    for(int numberIndex = 0; numberIndex < numbersCount; numberIndex++)
    {
        <div class="display-label">
            Number: @numberIndex = @Html.DisplayFor(m => m.Numbers[numberIndex])
        </div>
    }
}
</div>

This template simply displays the contents of the associated NameResponseModel object.

Next, in the Home Controller, I added the following action:

public ActionResult UpdateName(UpdateNameModel updateNameModel)
{
    return PartialView("DisplayTemplates/NameResponseModel", new NameResponseModel
    {
        Name = updateNameModel.Name,
        CurrentDateTime = DateTime.Now,
        Numbers = updateNameModel.Numbers.ToList()
    });
}

This action takes a UpdateNameModel object as a parameter and simply copies this into a new instance of the NameResponseModel. It then returns the display template as a partial view.

Finally, my Home/Index.cshtml view looks like this:

@{
    ViewBag.Title = "Home Page";
}

<script type="text/javascript">
    $(function () {
        $('#UpdateName').click(function () {
            var inputName = $('#Name').val();
            var dataResponse = { Name: inputName, Numbers: [1, 45, 67, 89] };
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(dataResponse),
                dataType: 'html',
                url: '@Url.Action("UpdateName")',
                success: function(result) {
                    $('#Response').html(result);
                }
            });
        });
    });
</script>


<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

<div id="Response"></div>

<input type="text" id="Name" />
<button type="button" id="UpdateName">Update</button>

I’ve added a div with the Id=”Response”. This will be used to display the partial view following an Ajax update. When the “Update” button is clicked, the click event creates a Json object with the contents of the “Name” text input and an array of integers. Note that the names of the Json items must match exactly the names within the data model that the Json will be bound to. MVC3 will quite happily handle complex data binding, so the array of integers will be bound successfully to the Numbers IEnumerable<int> parameter in the UpdateNameModel class.

Other points to note are the contentType parameter of the Ajax call is set to 'application/json; charset=utf-8'. This indicates that the parameter passed by the Ajax call will be a Json object. The Json object itself needs to be converted to a string, JSON.stringify will perform this function for us. The dataType parameter in the Ajax call is set to ‘html’. This indicates that the data returned by the server is expected to be html (the rendered partial view in this case). The success callback then simply loads this returned html into the “Response” div.

Hope this helps somebody! It took me a while, and a lot of googling, to figure it out!

Print | posted on Monday, August 6, 2012 10:23 PM | Filed Under [ C# ASP.NET MVC 3 Razor JQuery ]

Feedback

Gravatar

# re: Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

Thanks a ton for this blog, was trying to figure this out for a while
1/17/2013 7:33 AM | pp
Gravatar

# re: Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

Hi!

This is a nice article. Thank for sharing your knowledge. There are some other links related to "Calling partial view using Ajax in ASP.NET MVC 4". I hope this is a

very useful for developers.

http://www.mindstick.com/Articles/8e131adf-2621-4cd7-8557-770c1ede799c/?Calling%20partial%20view%20using%20Ajax%20in%20ASP.NET%20MVC%204

http://ciintelligence.blogspot.in/2012/06/aspnet-mvc-ajax-load-with-partial-view.html
5/8/2013 3:26 PM | Marcel Ethan
Gravatar

# re: Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

Hi !!

Thanks for this blog, it was amazing example to use jquery Ajax method to pass json.

thanks one more time.........
8/13/2013 6:24 AM | Mohd Saeed
Gravatar

# re: Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

Really Super!! Nice Article very very useful.. Thanks a lot...
10/21/2013 11:32 AM | Karthika
Gravatar

# re: Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

Very Good....
3/12/2014 10:16 AM | chet@n
Gravatar

# re: Using JQuery Ajax method to pass Json to a MVC3 Action and return a partial view

Good Articles
3/31/2014 1:08 PM | Ali
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: