Partial View using Unobtrusive Ajax in ASP.NET MVC 5 loads into a new page

.Net, ASP.NET, C#, MVC 0 Comments

Make sure you include the correct unobtrusive ajax package; you want this:http://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax
i.e., do this in the NuGet package manager console

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

don’t use this older one: http://www.nuget.org/packages/jQuery.Ajax.Unobtrusive

Also check you have unobtrusive ajax added into the project.

1. ./Views/Shared/_layouts.cshtml file should have the jqueryval bundle added to it, i.e.,

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval")
@RenderSection("scripts", required: false)
</body>
</html>

2. ./App_Start/BundleConfig.cs file should have the unobtrusive script added to the jqueryval bundle:

bundles.Add(newScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive*"));

3. your View should have an @Ajax.ActionLink something like this:

<div id="myPartialView">
@Ajax.ActionLink("Click here for the Partial View", "MyPartialView",
new AjaxOptions
{
    UpdateTargetId = "myPartialView",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "Get"
})
</div>

4. the Partial View (in my case called _AddressDetails.cshtml ) would be something like this:

@model MyAddressBook.Models.AddressBook
<div id="topSales-details">
    <p>Name: &nbsp; @Model.Name</p>
    <p>Email Address &nbsp; @Model.EmailAddress)</p>
</div>

5. the Controller should updated to include an action like:

public ActionResult AddressDetails()
{
    var addressDetails = GetAddressDetails();
    return PartialView("_AddressDetails", addressDetails);
}
private AddressBook GetAddressDetails()
{
    return db.AddressBook.OrderBy(b => b.Sales).First();
}

Leave a Reply

Your email address will not be published. Required fields are marked *