ASP.NET MVC - 使用多个模型查看 [英] ASP.NET MVC - View with multiple models

查看:29
本文介绍了ASP.NET MVC - 使用多个模型查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成这样的 HTML

I am trying to generate such HTML

    <form action="/some/process" method="post">
        <input type="hidden" name="foo.a" value="aaa"/>
        <input type="hidden" name="bar.b" value="bbb"/>
        <input type="submit" />
    </form>

所以它可以被这个Action处理:

so it can be processed by this Action:

    public ActionResult Process(Foo foo, Bar bar)
    {
        ...
    }

给定操作代码

    public ActionResult Edit()
    {
        ViewData["foo"] = new Foo { A = "aaa" };
        ViewData["bar"] = new Bar { B = "bbb" };

        return View();
    }

我应该在 Edit.aspx 视图中写什么?我不想手动编写名称foo.a"和bar.b".

what should I write in Edit.aspx view? I don't want to write names 'foo.a' and 'bar.b' manually.

推荐答案

String-indexed ViewData 不好.您可能想要做的是为您的多变量视图数据创建一个小包装类,并将其传递给强类型视图.IE:

String-indexed ViewData is bad. What you probably want to do is make a little wrapper class for your multi-variable view data and pass that to a strongly typed view. IE:

public class FooBarViewData
{
   public Foo Foo {get; set;}
   public Bar Bar {get; set;}
}
public ActionResult Edit()
{
   FooBarViewData fbvd = new FooBarViewData();
   fbvd.Foo = new Foo(){ A = "aaa"};
   fbvd.Bar = new Bar(){ B = "bbb"};
   return View(fbvd);
}

然后您的视图只是强类型为 FooBarViewData,您可以使用 Model 属性调用该对象的成员.

Then your view is just strongly typed to FooBarViewData and you can call members of that object using the Model property.

这篇关于ASP.NET MVC - 使用多个模型查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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