2

I'm using MVC 4 and submitting an Ajax form which I have verified is updating the model database sucessfully. I'm displaying a jQuery dialog to the user, who can edit the form fields within the dialog and then update or cancel.

Everything works fine, until I update the form. Instead of closing the jQuery dialog, I'm dumped onto a blank page with the Json return value from my Controller. Any ideas?

View:

@using (Ajax.BeginForm("Edit", "References", new AjaxOptions 
{
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "POST",
    OnSuccess = "updateSuccess"
}, new { @id = "updateCarForm" }))
{
//etcetera

Controller:

public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ReferencesData referencesData = db.ReferencesDatas.Find(id);
            if (referencesData == null)
            {
                return HttpNotFound();
            }
            return PartialView(referencesData);
        }

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "make, model, colour")] ReferencesData referencesData)
        {
            if (ModelState.IsValid)
            {
                db.Entry(referencesData).State = EntityState.Modified;
                db.SaveChanges();
                return Json(JsonResponseFactory.SuccessResponse("Woohoo"), JsonRequestBehavior.DenyGet);
            }
            else
            {
                return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
            }
        }

Javascript:

<div id="updateDialog" title="Update Car"></div>
    <script type="text/javascript">
        var linkObj;
        $(function () {
            $(".editLink").click(function () {
                //change the title of the dialog
                linkObj = $(this);
                var opt = {
                    autoOpen: false,
                    width: 1145,
                    height: 600,
                    resizable: false,
                    modal: true,
                    title: 'Edit Reference',
                    buttons: {
                        "Update": function () {
                            $("#update-message").html(''); //make sure there is nothing on the message before we continue
                            $("#updateCarForm").submit();
                        },
                        "Cancel": function () {
                            $(this).dialog("close");
                        }
                    }
                };

                var dialogDiv = $("#updateDialog").dialog(opt);
                var viewUrl = linkObj.attr('href');
                $.get(viewUrl, function (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 updateSuccess(data) {
            if (data.Success == true) {
                //we update the table's info
                var parent = linkObj.closest("tr");
                parent.find(".carName").html(data.Object.Name);
                parent.find(".carDescription").html(data.Object.Description);
                //now we can close the dialog
                $('#updateDialog').dialog('close');
                //twitter type notification
                $('#commonMessage').html("Update Complete");
                $('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
            }
            else {
                $("#update-message").html(data.ErrorMessage);
                $("#update-message").show();
            }
        }

    </script>
ma11achy
  • 133
  • 2
  • 14
  • The problem is the `AjaxHelper.BeginForm()` is set to replace the content as html instead of handle the response as JSON. See [this answer](http://stackoverflow.com/questions/304233/how-to-use-ajax-beginform-mvc-helper-with-json-result?lq=1). – Jasen Jan 28 '15 at 19:44
  • Hi Jasen, I tried adding var json = e.get_response().get_object(); alert(json.success); to my jQuery if thats what you were referring to, but still same problem. Any other insights gratefully accepted! – ma11achy Jan 28 '15 at 21:22
  • You'll need to modify your `AjaxOptions` a bit then specify a javascript function to handle the responses. Rather than the accepted answer on that question [the other answer](http://stackoverflow.com/a/7467032/2030565) is probably better in your case; I apologize for not being clear about that. However, I usually find it much easier to ditch the `AjaxHelper` and use **jQuery.post()** instead. – Jasen Jan 28 '15 at 21:47
  • Many thanks for the help, will give your suggestions a try tomorrow – ma11achy Jan 28 '15 at 22:02

2 Answers2

1

You need to catch the submit in JS.

$('form').submit(function(){
   //serialize form
   $.post(url,{formData}function(json){
      //do what you want with the json
   })
})

The way you have it will change the view because when you do a plain form submit it wants to change its view with what ever result it gets.

mattfetz
  • 439
  • 2
  • 11
0

Have you enabled Unobtrusivejavascript in your web.config

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

Needless to say that you have to include

jquery.unobtrusive-ajax.js
Oualid KTATA
  • 1,116
  • 10
  • 20