ASP.NET MVC - View with multiple models
You have a couple of choices. First, you can reference them from ViewData and use an HtmlHelper extension. Or you could create a view-specific model and use a strongly-typed viewpage for Edit.aspx.
public class EditModel
{
public Foo foo { get; set; }
public Bar bar { get; set; }
}
public ActionResult Edit()
{
var model = new EditModel();
model.foo = new Foo { A = "aaa" };
model.bar = new Bar { B = "bbb" };
return View( model );
}
(Edit.aspx is of type ViewPage<EditModel>
)
Either way, the HtmlHelper extension will pick up any initial values.
<form action="/some/process" method="post">
<%= Html.Hidden( "foo.A" ) %>
<%= Html.Hidden( "bar.B" ) %>
</form>
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);
}
Then your view is just strongly typed to FooBarViewData
and you can call members of that object using the Model
property.