ASP.NET MVC4 AJAX.BeginForm AjaxOptions OnSuccess not called

67,034

Solution 1

The below Jquery File is required

jquery.unobtrusive-ajax.js

Solution 2

Try:

@using (Ajax.BeginForm("Edit", new {controller = "Cars"} , new AjaxOptions

Solution 3

I had the same issue. Initially I had my script in the head section of the partial view... This was causing my issues.

I moved it to the header in view that was hosting my partial view and everything worked fine. My view is a bootstrap page hosted in a mvc application with the layout set to: "Layout = Nothing". If your controller action is loading a view, there is definitely a issue with the jquery.unobtrusive-ajax.js location...

Solution 4

You need to add one more parameter in your BeginForm call:

Ajax.BeginForm("Edit","Cars", null, new AjaxOptions
               {
                   InsertionMode = InsertionMode.Replace,
                   HttpMethod = "POST",
                   OnSuccess = "updateSuccess"
               }, new { @id = ""updateCarForm })

null is for RouteValueDictionary. Here are all overloads for Ajax.BeginForm method.

Share:
67,034
Admin
Author by

Admin

Updated on July 26, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to use Jquery Model Dialog in MVC4 using Razor dialog box showing fine but AjaxOptions.OnSuccess javascript function is not calling after i click the update button but it's redirected to http://<>:3738/Cars/Edit/1?Length=4 i don;t know why it was happened.

    Here is my Code

    CarController.cs

    public class CarsController : Controller
    {
        private ExpDb db = new ExpDb();
    
        //
        // GET: /Cars/
    
        public ActionResult Index()
        {
            return View(db.Cars.ToList());
        }
    
    
    
        //
        // GET: /Cars/Edit/5
    
        public ActionResult Edit(int id = 0)
        {
            CarModel carmodel = db.Cars.Find(id);
            if (carmodel == null)
            {
                return HttpNotFound();
            }
            return PartialView(carmodel);
        }
    
        //
        // POST: /Cars/Edit/5
    
        [HttpPost]
        public JsonResult  Edit(CarModel carmodel)
        {
            if (ModelState.IsValid)
            {
    
                db.Entry(carmodel).State = EntityState.Modified;
                db.SaveChanges();
                //return RedirectToAction("Index");
                 return Json(JsonResponseFactory.SuccessResponse(carmodel),JsonRequestBehavior.DenyGet);
            }
          else {
                return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
            }
        }
    

    Index.cshtml

    @model IEnumerable<AjaxSamples.Models.CarModel>
    
    @{
    ViewBag.Title = "Index";
    }
    <div id="commonMessage"></div>
    <p>
    @Html.ActionLink("Create New", "Create")
    </p>
    <table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ImageFileName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th></th>
    </tr>
    
    @foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ImageFileName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "editLink" }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    
            <button id="opener">Open Dialog</button>
        </td>
      </tr>
    
    
    
     }
    
    </table>
    
     <div id="updateDialog" title="Update Car"></div>
     <script type="text/javascript">
     var linkObj;
     $(function () {
        $(".editLink").button();
    
        $('#updateDialog').dialog({
            autoOpen: false,
            width: 400,
            resizable: false,
            modal: true,
            buttons: {
                "Update": function () {
                    $("#update-message").html(''); //make sure there is nothing on the message before we continue                         
                    $("#updateCarForm").submit();
                },
                "Cancel": function () {
                    alert('sd');
                    $(this).dialog("close");
                }
            }
        });
    
        $(".editLink").click(function () {
            //change the title of the dialog
            linkObj = $(this);
            var dialogDiv = $('#updateDialog');
            var viewUrl = linkObj.attr('href');
            $.get(viewUrl, function (data) {
                alert(data);
                dialogDiv.html(data);
                //validation
                var $form = $("#updateCarForm");
                // Unbind existing validation
                $form.unbind();
                $form.data("validator", null);
                // Check document for changes
                $.validator.unobtrusive.parse(document);
                // Re add validation with changes
                $form.validate($form.data("unobtrusiveValidation").options);
                //open dialog
                dialogDiv.dialog('open');
            });
            return false;
        });
    
    });
    function err(data) {
        alert(data);
    }
    
    
     function updateSuccess(data) {
        alert(data);
    }
    

    Edit.cshtml

    @model AjaxSamples.Models.CarModel
    
    @{
    ViewBag.Title = "Edit";
    }
    
    @using (Ajax.BeginForm("Edit", "Cars", new AjaxOptions
        {
            InsertionMode = InsertionMode.Replace, 
            HttpMethod = "POST",
            OnSuccess = "updateSuccess"
        }, new { @id = "updateCarForm" }))
     {
     @Html.ValidationSummary(true)
    <div id="update-message" class="error invisible"></div>
    <fieldset>
        <legend>CarModel</legend>
    
        @Html.HiddenFor(model => model.Id)
    
        <div class="editor-label">
            @Html.LabelFor(model => model.ImageFileName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ImageFileName)
            @Html.ValidationMessageFor(model => model.ImageFileName)
        </div>
    
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
    
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
    
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
    }
    
    <div>
    @Html.ActionLink("Back to List", "Index")
    </div>
    
  • Admin
    Admin over 10 years
    Thanks for your quick reply. but what is the actual issue in the current code.
  • Admin
    Admin over 10 years
    Thanks for your reply. I've replaced the code but still same issue
  • rexcfnghk
    rexcfnghk over 10 years
    Why are you changing the OP's Ajax.BeginForm() to Html.BeginForm()?
  • Admin
    Admin over 10 years
    still not working here with i have uploaded my complete source code to you [link]rvmicro.com/Ajaxsamples.rar
  • Admin
    Admin over 10 years
    here with i have uploaded my complete source code for you [link]rvmicro.com/Ajaxsamples.rar
  • rexcfnghk
    rexcfnghk over 10 years
    @ravikumar what isn't working? Is there exception being thrown? Script errors? Use the debugging tools from Google Chrome or Fiddler to give more details.
  • Admin
    Admin over 10 years
    there is no exception being thrown. it's simply redirect to localhost:3738/Cars/Edit/1?Length=4 and given json data.
  • rexcfnghk
    rexcfnghk over 10 years
    Did you include the null? If you have it shouldn't be redirecting with the query string
  • Admin
    Admin over 10 years
    yes i did it's redirected without query string but "updateSuccess" javascript not called.
  • Anand Thakkar
    Anand Thakkar over 10 years
    In my suggestion i am not using Ajax i suggest him the other solution of the Post method for that i place Html.BeginForm() at there.
  • Admin
    Admin over 10 years
    I've identified the issue. it's the problem with Jquery version previously i've used jquery1.9.1.js now i've changed to jquery-1.7.1.js. it's working fine. but i don't understand why it's causing the higher version of jquery.
  • decompiled
    decompiled almost 10 years
    This worked for me. It is not included in the mvc5 template by default.
  • Nimit Joshi
    Nimit Joshi about 9 years
    Thanks. You saved my time
  • Baxter
    Baxter almost 9 years
    I spent hours trying to get Ajax.BeginForm working. Your post solved the problem for me.