Binding models to view
I would like to Bind two models (say ModelA and Mode开发者_运维问答lB classes) to a view.ascx page. And each of these classes have List objects that I would like to access in view. I know we can access one class by associating strongly typed model to one of the classes. How do I bind the other class?
Simply create a ViewModel - class containing all models you need (in this case ModelA and ModelB). Then bind the view to this ViewModel and access it like model.ModelA.Property
in your view.
Edit: You wrote that both ModelA and modelB has their collections? So you create something like:
public class ABViewModel
{
public ModelA A {get;set;}
public ModelB B {get;set;}
}
Then instantiate it in controller like:
ABViewModel abvm = new ABViewModel();
abvm.A = new ModelA();
abvm.B = new ModelB();
And return your view (strongly typed to ABViewModel).
return View(abvm);
And access your properties in View:
foreach (var item in model.A.CollectionProperty) // something like this
Or
model.B.Property // something like this
Ie. you can access both .. ModelA and ModelB, because they are now properties of another object - your new model.
Note: I am not sure, if you use model.
or Model.
in mvc2 to acces your model. It's model
in mvc3.
You write a third class wrapping those two lists:
public class MyViewModel
{
public IList<Foo> List1 { get; set; }
public IList<Bar> List2 { get; set; }
}
and then you use this class as a view model passed to the view. Then inside the view you can access both lists:
<% foreach(var item in Model.List1) { %>
...
<% } %>
<% foreach(var item in Model.List2) { %>
...
<% } %>
精彩评论