MVC 4 Ajax.beginform submit - causes a full postback

Internet project MVC4

I use Ajax.BeginForm to do a postback with validation, and it returns the whole page, not just UpdateTargetID. I looked at other posts on SO and did not find an answer. I built a new MVC4 Internet project for testing purposes only (VS 2012 was updated using "ASP.NET and Web Tools 2012.2").

Here is my code

controller

public ActionResult Index() { var vM = _db.Students.FirstOrDefault(); return View(vM); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(Student vM) { if (ModelState.IsValid) { //code if Model valid return Json(new { url = Url.Action("About", "Controller") }); } ModelState.AddModelError(string.Empty, "AJAX Post"); return PartialView("Index", vM); } 

View

 @model AJAX_Test.Models.Student @{ ViewBag.Title = "Student"; } <script src="~/Scripts/jquery-1.8.2.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> <script type="text/javascript"> var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } } // when server returns JSON object containing an url property redirect the browser </script> <h1>@ViewBag.Title</h1> <div id="IDXForm"> @using (Ajax.BeginForm("Index", new AjaxOptions() { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess", HttpMethod = "Post" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <span>@Html.EditorFor(m => m.FirstName) @Model.EnrollmentDate.ToShortDateString()</span> <input type="submit" value="Submit" /> } </div> 

Initial view: enter image description here

After sending: enter image description here

The source code for the body after sending:

  <div id="body"> <section class="content-wrapper main-content clear-fix"> <script src="/Scripts/jquery-1.8.2.js"></script> <script src="/Scripts/jquery.unobtrusive-ajax.js"></script> <script type="text/javascript"> var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } } // when server returns JSON object containing an url property redirect the browser </script> <h1>Student</h1> <div id="IDXForm"> <form action="/" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="onSuccess" data-ajax-update="#IDXForm" id="form0" method="post"><input name="__RequestVerificationToken" type="hidden" value="vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1" /><span><input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="Carson" /> 9/1/2005</span> <input type="submit" value="Submit" /> </form></div> " post "> <input name =" __ RequestVerificationToken "type =" hidden "value =" vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1 "/> <span> <input class =" text-box single-line "  <div id="body"> <section class="content-wrapper main-content clear-fix"> <script src="/Scripts/jquery-1.8.2.js"></script> <script src="/Scripts/jquery.unobtrusive-ajax.js"></script> <script type="text/javascript"> var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } } // when server returns JSON object containing an url property redirect the browser </script> <h1>Student</h1> <div id="IDXForm"> <form action="/" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="onSuccess" data-ajax-update="#IDXForm" id="form0" method="post"><input name="__RequestVerificationToken" type="hidden" value="vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1" /><span><input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="Carson" /> 9/1/2005</span> <input type="submit" value="Submit" /> </form></div> 

Can anyone understand what is wrong with my code?

Thanks.

+7
source share
6 answers

The contents of the UpdateTargetID must be in the partial view and that the partial view must be called from the Controller action. Darin answered me by email (thanks Darin). You need to use the view in the paragraph. I tried to double-update his answer, and the moderators did not do this or explained why I am posting my own answer to others.

_MyForm View:

 @model AJAX_Test.Models.Student @using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <span> @Html.EditorFor(m => m.FirstName) @Model.EnrollmentDate.ToShortDateString() </span> <input type="submit" value="Submit" /> } 

The main view:

 <div id="IDXForm"> @Html.Partial("_MyForm") </div> 

Controller Actions:

  ModelState.AddModelError(string.Empty, "AJAX Post"); return PartialView("_MyForm", vM); 
+9
source

A few things that come to mind can cause this behavior:

  • In your question, you indicated the registration of your packages, but did you really include them in your opinion or in the layout? Make sure you include jquery.js first in your view or layout, and then jquery.unobtrusive-ajax.js (in that order):

     @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") 
  • jquery.unobtrusive-ajax.js script is incompatible with jquery 1.9 and later since it relies on .live() , which was removed in jQuery 1.9 . Therefore, if for some reason you upgraded the jQuery version to version 1.9 or later, which will not work. You must refuse.

  • In your onSuccess callback, you are redirected to the URL if the controller action returns JSON. Have you confirmed that this is not so? Because when a redirect occurs using window.location.href , it is pretty normal that you get a full page reload, not a partial refresh

In all cases, use the javascript debugging tool to find out what exactly is happening. If you use Firefox, you can use FireBug. If you use Google Chrome, you can use the Chrome Developer Toolbar. Look at the console for possible JavaScript errors. Take a look at the network tab to see if all javascripts have loaded successfully and you don't have 404 errors. Learn how to debug javascript code with a tool. You will be surprised how much information about potential problems that may arise with your code, these tools will provide you.

+11
source

use: <script src="../Scripts/jquery.unobtrusive-ajax.js"></script>

This JS does the work of Ajax.

+1
source

make sure you have the configuration of your packages, including

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery-{version}.js")); 

bundles.Add (new ScriptBundle ("~ / bundles / jqueryval"). Include ("~ / Scripts / jquery.validate *"));

+1
source

At a minimum, you need these two options:

 @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") 

And if that still doesn't help, check in web.config and make sure that unobtrusive is enabled:

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

And if this still doesn’t work, make sure that the unobtrusive js files are compatible with the current version of jQuery, regardless of the version of jQuery you are using, which can be found at the URL below:

http://www.nuget.org/packages?q=unobtrusive

0
source

A few other points.

  • jquery.unobtrusive-ajax.js now supports jQuery 1.9. I installed jquery.unobtrusive-ajax.js version 3.0.0 and works with jQuery 1.9

2. Ensure that all children are closed correctly, including the view containing Ajax.BeginForm and the main view. Also, if you have @ Html.Raw () in the main view or inside the view that contains Ajax.BeginForm, be careful with this too.

Wiring is here to keep one day scratching your head.

0
source