简体   繁体   English

在asp MVC 5中将多个模型从视图传递到控制器

[英]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 :更新这里是我的解决方案对我有用:我创建了两个子视图,一个用于 Model1,一个用于 Model2,在大视图模型中,我通过以下方式呈现它们:

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

and in the controller I have Action method like this在控制器中我有这样的 Action 方法

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

and I have Action method for posting like this :我有像这样发布的 Action 方法:

  [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然后创建了一个类型为 (BigViewModel) 的强类型视图,以便用户可以编辑该视图中的字段并按下提交按钮返回服务器进行处理
public ActionResult test(BigViewModel model)

but the model is null.但模型为空。 I need a way to pass the BigViewModel to the controller.`我需要一种方法将 BigViewModel 传递给控制器​​。`

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 操作方法

    [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它在我身边工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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