Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax.BeginForm OnSuccess not firing

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)); }
like image 713
ThunderDev Avatar asked Oct 14 '14 13:10

ThunderDev


2 Answers

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.

like image 181
Andrew Whitaker Avatar answered Oct 20 '22 19:10

Andrew Whitaker


Add reference to the following js libraries:

  • jquery-{version}.min.js
  • MicrosoftAjax.js
  • MicrosoftMvcAjax.js
  • jquery.validate.min.js
  • jquery.validate.unobtrusive.js
  • jquery.unobtrusive-ajax.js
like image 24
Hamid Narikkoden Avatar answered Oct 20 '22 19:10

Hamid Narikkoden