简体   繁体   中英

Passing multiple models from View to Controller in asp MVC 5

Update here is my solution that worked for me: I create two sub views one for Model1 and one for Model2 and in the big view model I render them by :

@{Html.RenderPartial("view1", Model.model1);}
@{Html.RenderPartial("view2", Model.model2);}

and in the controller I have Action method like this

BigViewModel model= new BigViewModel();
  return View(model);

and I have Action method for posting like this :

  [HttpPost]
     public ActionResult fun(Model1 model1,Model2 model2)
{
//Logic go here
}

=================================

I have a 2 models like this :

public class Model1 {
    ... more properties here ...
}

public class Model2 {
    ... more properties here ...
}

and then I created one big model : `

    public class BigViewModel {
    public Model1 model1 { get; set; }
    public Model2 model2{ get; set; }
}

then created a strong typed view of type (BigViewModel) so that user can edit the fields in that view and press submit button to back to server to process
public ActionResult test(BigViewModel model)

but the model is null. I need a way to pass the BigViewModel to the controller.`

I have models like this

public class Model1
{
    public int Id { get; set; }
}

public class Model2
{
    public int Id { get; set; }

}

public class BigViewModel
{
    public Model1 model1 { get; set; }
    public Model2 model2 { get; set; }
}

I have httppost action method like this

    [HttpPost]
    public ActionResult Test(BigViewModel vm)
    {
        if (vm == null)
        {
            throw new Exception();
        }
        return View();
    }

I have razor view like this

@model WebApplication2.Models.BigViewModel

@{
    ViewBag.Title = "Test";
}

<h2>Test</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>BigViewModel</h4>
        <hr/>
        @Html.ValidationSummary(true, "", new {@class = "text-danger"})
        @Html.EditorFor(s => s.model1.Id)
        @Html.EditorFor(s => s.model2.Id)
    </div>


    <button type="submit">Save</button>
}

   <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

It works on my side

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM