MVC asp.net: submit multiple forms

When submitting one form from a view, how can I read or read controller data in another form on one page?

+5
source share
4 answers

When you submit the form in a browser, it will only send data for the fields inside this <form> </form>. This is true regardless of the back-end technology you use, be it ASP.net, MVC.net, PHP, Python, etc.

The only two options that I really can think of:

  • As with WebForms, just place a <form> around the entire page and sort the results later based on the click of a button.
  • Javascript/AJAX , , , . (, ), .

, , .

+10

Ajax Javascript...

<SCRIPT language="JavaScript">
function submitforms()
{
        new Ajax.Request(formUrl,
        {
            parameters: $H({param1:value,param2:value}).toQueryString(),
            method: 'post',
            onSuccess: function(transport) {
               document.myform.submit();
            }
        }
}
</SCRIPT> 
+2

. , , . JavaScript .

+1
        var formData1 = $("#form1").serializeObject();
        var formData2 = $("#form2").serializeObject();
        $.extend(formData1, formData2);
        var formData = JSON.stringify(formData1);

        $.ajax({
            type: "POST",
            url: "@Url.Action("MyAction", "MyController")",
            data: formData,
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                ...Do something with the data
            },
            error: function(result) {
                ...Handle the error
            }
        });

Then on the side of your controller (I use MVC, but WebAPI will probably work the same way) you can declare two separate parameters that correspond to your client models, and everything will be parsed for you, that is, it is assumed that t have matching property names! Gotta love him when magic happens!

public ActionResult MyAction(FormDataModel1 formData1, FormDataModel2 formData2)

Confirm https://github.com/macek/jquery-serialize-object for serializeObject code.

0
source

All Articles