1

In my project I have multiple forms on same page which I want to pass in one go to controller. How to achieve that?

<script>
function onSaveButtonClicked() {
    var form = $("#SaveForm").serialize();
    var form2 = $("#SaveForm").serialize();


    $.ajax({
        url: '@Url.Action("Filter","SearcherEngine")',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({ model: form, model2: form2 }),
        cache: false,
        success: function (result) {
            alert(result);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });

};

[HttpPost]
public ActionResult Filter(MyViewMOdel model,MyViewModel2 model2)
{
}
tereško
  • 58,060
  • 25
  • 98
  • 150
user1075940
  • 1,086
  • 2
  • 22
  • 46

2 Answers2

1

What makes this complex is the different view models per form. As a result, you cannot simply use an array and map to a list of a common class.

Keep in mind that model binding is done based on the structure of the object passed (posted in this case). So what you need to do is create a model that can hold the structure of what you want to pass in c#, and then also create that same structure in javascript to pass in.

public class ViewModelSet
{
 public MyViewModel model1 { get; set; }
 public MyViewModel1 model2 { get; set; }
}

Now you need to recreate this structure with the exact same naming for properties in javascript

var form1 = ...;
var form2 = ...;

var modelSet = {};
modelSet.model1 = form1;
modelSet.model2 = form2;

Next pass this in (only the name of the parameter must match the name of the expected parameter server side)

data: { model : modelSet },

And expect this to be passed server side

public ActionResult FilterNCTS(ViewModelSet model)
{
  //Now you should be able to have access to nested models
  // TODO: work with model.model1
  ...
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

I joined both models in one, and wrapped partial views around one form.

class MyModel
{
   ...
}

    @model MyModel;
    @using(Html.BeginForm())
    {
         Html.RenderPartial("Path",Model);
         Html.RenderPartial("Path",Model);   
    }
user1075940
  • 1,086
  • 2
  • 22
  • 46