Tuesday, June 10, 2014

Resolve ASP.NET MVC 4 Ajax.BeginForm full postback

I recently spent several hours trying to resolve a problem where my view using Ajax.BeginForm kept posting back a full view instead of inserting the results of an AJAX partial postback into my existing view.  I searched for hours and could not find what was wrong:

web.config appSettings were correct:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />


Microsoft jQuery Unobtrusive Ajax NuGet package installed and bundled:


1 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
2 "~/Scripts/jquery.unobtrusive*",
3 "~/Scripts/jquery.validate*"));
4

Simple test controller:


1 public class TestAjaxController : Controller
2 {
3 public ActionResult TestAjaxIndex()
4 {
5 return View();
6 }
7
8 [HttpPost]
9 public PartialViewResult GetTestAjax()
10 {
11 return PartialView("_GetTestAjax");
12 }
13 }


View (TestAjaxIndex.cshtml) created:


1 @{
2 ViewBag.Title = "TestAjaxIndex";
3 }
4
5 <h2>TEST AJAX</h2>
6
7 <div id="testAjax"></div>
8
9 @using (Ajax.BeginForm("GetTestAjax", new AjaxOptions() {
10 UpdateTargetId = "testAjax", InsertionMode = InsertionMode.Replace }))
11 {
12 <input type="submit" value="Test" />
13 }
14
15 @Scripts.Render("~/bundles/jqueryval")

Partial view (_GetTestAjax.cshtml) created:


1 <span>GOT IT</span>

Whenever I submitted \TestAjax\TestAjaxIndex it would do a full postback to \TestAjax\GetTestAjax and show my “GOT IT” span, rather than inserting my “GOT IT” span into my “testAjax” div.


It turns out the problem is that I have a _Layout.cshtml view which renders my TestAjaxIndex view inside the body using @RenderBody(), and I neglected to render my “~/bundles/jqueryval” script bundle inside of a Scripts section.  Therefore my jquery.unobtrusive-ajax.js resource was loaded AFTER my jquery-1.10.2.js resource.


Here is the corrected version of my TestAjaxIndex.cshtml which solved my problem:


1 @{
2 ViewBag.Title = "TestAjaxIndex";
3 }
4
5 <h2>TEST AJAX</h2>
6
7 <div id="testAjax"></div>
8
9 @using (Ajax.BeginForm("GetTestAjax", new AjaxOptions() {
10 UpdateTargetId = "testAjax", InsertionMode = InsertionMode.Replace }))
11 {
12 <input type="submit" value="Test" />
13 }
14
15 @*use a Scripts section to fix the problem*@
16 @section Scripts {
17 @Scripts.Render("~/bundles/jqueryval")
18 }

1 comment:

  1. Only this below line is fixing the problem

    @*use a Scripts section to fix the problem*@
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    }
    Thanks alot

    ReplyDelete