ross dickinson: web and desktop software developer

Submitting a Nested Form in ASP MVC3

by Ross on February 3, 2012 at 7:06 PM under .NET | ASP.Net | MVC

In case you're using the jQuery unobtrusive ajax library with your ASP MVC3 site, you'll probably find that it can be difficult to submit a nested form in certain situations. The problem comes from this bit of code:

$("form[data-ajax=true]").live("submit", function (evt) {
    var clickInfo = $(this).data(data_click) || [];
    evt.preventDefault();
    if (!validate(this)) {
        return;
    }
    asyncRequest(this, {
        url: this.action,
        type: this.method || "GET",
        data: clickInfo.concat($(this).serializeArray())
    });
});

When your nested form's submit event gets raised, it bubbles up to the parent form as well. You can fix this in two ways. The easiest way is to modify the code above to look like this:

$("form[data-ajax=true]").live("submit", function (evt) {
    if (evt.currentTarget != evt.target) { return; }
    var clickInfo = $(this).data(data_click) || [];
    evt.preventDefault();
    if (!validate(this)) {
        return;
    }
    asyncRequest(this, {
        url: this.action,
        type: this.method || "GET",
        data: clickInfo.concat($(this).serializeArray())
    });
});

This stops the unobtrusive ajax library's handler from submitting the wrong form.

Another way is to add your own submit handler to your nested form that calls evt.stopPropagation(). This tells the event to stop bubbling up and calling other event handlers. This can be tricky, though, because you have to ensure that your handler is called before the unobtrusive handler.

Add comment

biuquote
  • Comment
  • Preview
Loading

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github