Reputation: 65
I'm looking for a way to populate more than 1 table in MVC, because the method only allows me to return One ModelView or I don't know how to return more. Do I have to build the table in the controller and store into a ViewData and display the viewData in the page?
Edit: Sorry, I think I didn't express the idea. The point is that I want to populate 2 or more datatables in the page.
For example, if I have a Customer and that Customer has 5 Contacts and 5 Addresses, I want to display the Customer Information and 2 Tables with Contacts and Addresses.
for each p in modelview
{
"<td>" + p.Name + "</td>"
}
for each p2 in modelview2
{
"<td>" + p2.Product + "</td>"
}
Upvotes: 1
Views: 387
Reputation: 532565
You can return more than one model, but it will require a compound model for the view and the use of prefixes when binding the controller parameter.
Say you have a View Model that is:
public class VM
{
public FooClass Foo { get; set; }
public BarClass Bar { get; set; }
}
Then in your controller, you would have
public ActionResult MyAction( [Bind(Prefix="Foo")]FooClass foo,
[Bind(Prefix="Bar")]BarClass bar )
{
...
}
And in your view you would use:
<%= Html.TextBox( "Foo.Value" ) %>
<%= Html.TextBox( "Bar.Name" ) %>
Upvotes: 0
Reputation: 1063298
ViewData is a dictionary; you can store multiple items in there, simply via:
ViewData["foo"] -= ...
ViewData["bar"] -= ...
You can then get these (separately) in the view. The other approach is to declare a type that encapsulates both properties, and use an instance of that type as the model (and a typed view). Personally, I prefer the simple key/cast approach.
Upvotes: 2