7
votes

MVC4 Internet project

I'm using Ajax.BeginForm to do a Postback with validation and it posts back the entire page rather than just the UpdateTargetID. I've looked at other posts on SO and haven't found the answer. I've built a new MVC4 Internet project just for testing (VS 2012 has been updated with 'ASP.NET and Web Tools 2012.2').

Here's 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>

The initial view is: enter image description here

After Submittal: enter image description here

Source code for body after submittal:

        <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 see what is wrong with my code?

Thank you.

6

6 Answers

11
votes

A couple of things that come to mind that might be causing this behavior:

  1. In your question you have shown your bundle registrations but have you actually included them in your view or Layout? Make sure that in your view or layout you have first included jquery.js and then jquery.unobtrusive-ajax.js (in that order):

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    
  2. The jquery.unobtrusive-ajax.js script is not compatible with jquery 1.9 and later because it relies on the .live() which has been removed in jQuery 1.9. So if for some reason you have upgraded your jQuery version to 1.9 or later that won't work. You should downgrade.

  3. In your onSuccess callback you are redirecting to an url if the controller action returns a JSON. Have you verified that this is not the case? Because when a redirect happens using the window.location.href it's pretty normal that you get a full page reload and not a partial update

In all cases use a javascript debugging tool to see what exactly is happening. If you are using Firefox, then you could use FireBug. If you are using Google Chrome, you could use the Chrome Developer Toolbar. Look at the console for potential javascript errors you might have. Look at the network tab to see whether all javascripts are successfully loaded and you don't have 404 errors. Learn how to debug your javascript code with a tool. You will be surprised how much information about potential issues you might have with your code those tools will provide you.

9
votes

The contents of the UpdateTargetID must be in a partial view and that partial view needs to be called from the Controller Post Action. Darin answered me through e-mail (thank you Darin). You need to use a parital view. I've tried to update his answer twice and the moderators have not done it or provided an explanation why so I'm posting my own answer for others benefit.

_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" />                                                                                                     
}

Main View :

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

Controller Post Action:

  ModelState.AddModelError(string.Empty, "AJAX Post");
  return PartialView("_MyForm", vM);
1
votes

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

This JS is what makes Ajax work.

1
votes

Couple of other things to note.

  1. jquery.unobtrusive-ajax.js now supports JQuery 1.9. I have installed jquery.unobtrusive-ajax.js version 3.0.0 and it is working with JQuery 1.9

2. Make sure all the div tages are closed properly, including the view which contains the Ajax.BeginForm and the main view. Also if you have @Html.Raw() in the main view or inside the view which contains Ajax.BeginForm be cautious about that too.

Posting here to save one day of head scratching.

1
votes

make sure you have your bundles config include this

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

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

0
votes

At a minimum, you need these two includes:

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

And if that still does not help, check in web.config and make sure unobtrusive is enabled:

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

And if that still has no effect, make sure unobtrusive js files are compatible with current jQuery version, whatever version of jQuery you are using, which can be found at a below URL:

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