ASP视图中的多个模型

时间:2015-05-18 14:22:34

标签: c# asp.net asp.net-mvc

我有一个ASP / MVC视图,它显示模型中的数据,还包含一个部分视图,其中包含使用不同模型的表单。我有办法将这些结合到一个视图中吗?结果是显示值基于模型A,但页面中的表单提交模型B.这可能吗?

2 个答案:

答案 0 :(得分:1)

如果两者密切相关,您可以使用视图模型在视图中使用它们:

public class FooViewModel
{
    public SomeModelForDisplay Foo { get; set; }
    public SomeModelForForm Bar { get; set; }
}

在您的操作中,初始化两者:

public ActionResult Foo(int id)
{
    var foo = db.Foos.Find(id);
    if (foo == null)
    {
        return new HttpNotFoundResult();
    }

    var model = new FooViewModel
    {
        Foo = foo,
        Bar = new SomeModelForForm()
    };
    return View(model);
}

如果这两件事完全无关,或者特别是,如果在布局而不是直接视图中调用partial,则使用子操作更合适。基本上,你只需要处理显示部分就像没有其他事情一样:

public ActionResult Foo(int id)
{
    var foo = db.Foos.Find(id);
    if (foo == null)
    {
        return new HttpNotFoundResult();
    }

    return View(foo);
}

然后,您将添加另一个操作来处​​理表单:

[ChildActionOnly]
public ActionResult SomeForm()
{
    var model = new SomeModelForForm();
    return PartialView("_SomeForm", model);
}

然后,添加局部视图以仅渲染表单:

<强>视图\富\ _SomeForm.cshtml

@model SomeModelForForm

<!-- form fields here -->

然后,在您的视图/布局中 - 基本上您希望实际显示表单的位置:

@Html.Action("SomeForm", "Foo")

其中"Foo"这里是此子操作所在的控制器的名称。

答案 1 :(得分:0)

我建议你使用包含模型B和C的模型A.加载页面时加载B,加载部分加载。

另一个解决方案是你有一个模型A(给予剃刀页面),然后使用partial将模型B添加到页面然后它返回A和B的混合。你只需要注意命名这些字段是为了使模型绑定正常工作,例如

A有

  • 的firstName
  • lastName

和B有

  • 电话

然后,如果你为两个字段设置了edirot,那么可以在控制器中接收的模型可以是具有

的模型C.
  • 的firstName
  • lastName
  • 电话
相关问题