Ajax.BeginForm OnSuccess not firing

ThunderDev picture ThunderDev · Oct 14, 2014 · Viewed 19.2k times · Source

I'm using this partial view

@model CreateConfigEntityModel

<div class="row">
@using (Ajax.BeginForm("AddElement", "MerchantSites", new { merchantId = @Model.MerchantId }, new AjaxOptions
{
  HttpMethod = "POST",
  OnSuccess = "alert('ok')"
},
new { id = "addConfigForm" }
))
{
  @Html.LabelFor(m => m.EntityName)
  @Html.TextBoxFor(m => m.EntityName)
  @Html.ValidationMessageFor(m => m.EntityName)

  @Html.LabelFor(m => m.DefaultValue)
  @Html.TextBoxFor(m => m.DefaultValue)
  @Html.ValidationMessageFor(m => m.DefaultValue)

  <input type="submit" value="Ajouter" class="tiny button" /> 
}
</div>

Controller

public JsonResult AddElement(CreateConfigEntityModel model)
{
    if (ModelState.IsValid)
    {
        _merchantSitesManager.AddEntity(model.EntityName, model.DefaultValue);
        return Json(new { code = 1 }, JsonRequestBehavior.AllowGet);
    }
    else
        return Json(new { code = 0 }, JsonRequestBehavior.AllowGet);
}

This is what shows after submitting the form (item gets added correctly)

enter image description here

Not sure what I'm doing wrong.

Using jQuery JavaScript Library v2.1.1

I have in my web.config

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

I'm calling my partial view like this

@{ Html.RenderPartial("_CreateConfigEntity", new CreateConfigEntityModel(Model.MerchantId)); }

Answer

Andrew Whitaker picture Andrew Whitaker · Oct 14, 2014

Assuming you have a brand new project, you need to do the following things to get this working. The ASP.NET MVC template does not support unobtrusive AJAX out of the box:

  1. Add the "Microsoft.jQuery.Unobtrusive.Ajax" package from Nuget into your project. You can do this by right-clicking on the project and choosing "Manage Nuget Packages."
  2. Add "jquery.unobtrusive-ajax.js" to your page. If you're using the "bundling" feature in System.Web.Optimization, one easy way would be to add it to the jQuery bundle:

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

    You can also just add a <script> tag that points to the script.

Assuming the page is loading jQuery and jquery.unobtrusive-ajax.js, the code you posted should work.