Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - View with multiple models

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> 

so it can be processed by this Action:

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

Given the Action code

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

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

like image 469
alex2k8 Avatar asked Jun 03 '09 11:06

alex2k8


People also ask

Can we have 2 models in a single view?

In MVC we cannot pass multiple models from a controller to the single view.

Can a view have multiple models?

Introduction. In MVC, we cannot use multiple model tag on a view. But many times, we need to pass multiple models from controller to view or we want to show data from multiple model on a view.

How can we return multiple models to a view in ASP.NET MVC?

We have two ways to display these models together on one view using MVC structure. Create another class that will hold Userprofile and Employee, now write the below code to controller that will return MergeModel class to view. By Using Tuples we can include two or more than two models in a single view.


1 Answers

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.

like image 154
Wyatt Barnett Avatar answered Oct 09 '22 04:10

Wyatt Barnett