Passing multiple models from View to Controller in asp MVC 5

自古美人都是妖i 提交于 2019-12-12 07:02:38

问题


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.`


回答1:


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



来源:https://stackoverflow.com/questions/41661138/passing-multiple-models-from-view-to-controller-in-asp-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!