Load Partial View as Html By using jQuery – Ajax in ASP.NET MVC

Introduction

In ASP.NET MVC we can return a Partial View in the form of PartialViewResult using the PartialView method.
The following example shows Partial update scenarios using Ajax.Using jQuery to load the contents of a PartailView in to the current view using an Ajax call. In this example i have load a simple grid using Ajax.
Controller and Action Result

public class PartialController : Controller
{
public ActionResult GetPartialResult()
{
var list = new List<Album>
{
new Album {Title = "Album1"},
new Album {Title = "Album2"},
new Album {Title = "Album3"},
new Album {Title = "Album4"}
};
return PartialView(list);
}

}

public class Album
{
public string Title { get; set; }
}

Right click the ActionResult and Create a PartialView like below
@model IEnumerable<Mvc4Demos.Controllers.Album>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
</tr>
}
</table>

Here when a button click load the PartialViewResult by using Ajax and Append in to a Result div
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#result').load('/Partial/GetPartialResult');
});
});

</script>
<input type="button" id="btn" value="PartialExample"/>
<div id="result"></div>

Enjoy Reading…

5 thoughts on “Load Partial View as Html By using jQuery – Ajax in ASP.NET MVC

  1. Hi Jameel M.
    I have a doubt. Where should I write ,button,.I have written it in a Index.cshtml (view which should load partial view on button click) of Index Action method.

    Didn’t get the output.
    Please explain.

    Thanks a lot ,in advance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s