1

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>"
}

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

For simply getting data to the view (list/show), I would agree. This approach isn't always the simplest when getting data from the view (new/update), though. Especially, if you already have a compound model, say User with related Contacts.
foor and bar value will be the html code for a binded datatable?
No; they are whatever data you put in them; the view creates html, not the controller
0

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" ) %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.