在ASP MVC 5中将多个模型从View传递到Controller [英] Passing multiple models from View to Controller in asp MVC 5

查看:80
本文介绍了在ASP MVC 5中将多个模型从View传递到Controller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新 这是对我有用的解决方案: 我创建两个子视图,一个用于Model1,一个用于Model2. 在大视图模型中,我通过以下方式渲染它们:

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);}

在控制器中,我有这样的Action方法

and in the controller I have Action method like this

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

并且我有Action方法可以像这样发布:

and I have Action method for posting like this :

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

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

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

我有2个这样的模型:

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; }
}

然后创建一个类型强的类型化视图(BigViewModel) 这样用户可以在该视图中编辑字段,然后按Submit按钮返回服务器以进行处理
public ActionResult test(BigViewModel model)

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)

,但模型为空. 我需要一种将BigViewModel传递给控制器​​的方法.

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

推荐答案

我有这样的模型

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; }
}

我有这样的httppost操作方法

I have httppost action method like this

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

我有这样的剃刀视图

@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")
}

它在我这边工作

这篇关于在ASP MVC 5中将多个模型从View传递到Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆