Two models in one view in ASP MVC 3

2018-12-31 16:49发布

问题:

I have 2 models:

public class Person
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}
public class Order
{
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

I want edit objects of BOTH classes in SINGLE view, so I need something like:

@model _try2models.Models.Person
@model _try2models.Models.Order

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x=>x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

This, of course, don\'t work: Only one \'model\' statement is allowed in a .cshtml file. May be there is some workaround?

回答1:

Create a parent view model that contains both models.

public class MainPageModel{
    public Model1 Model1{get; set;}
    public Model2 Model2{get; set;}
}

This way you can add additional models at a later date with very minimum effort.



回答2:

To use the tuple you need to do the following, in the view change the model to:

@model Tuple<Person,Order>

to use @html methods you need to do the following i.e:

@Html.DisplayNameFor(tuple => tuple.Item1.PersonId)

or

@Html.ActionLink(\"Edit\", \"Edit\", new { id=Model.Item1.Id }) |

Item1 indicates the first parameter passed to the Tupel method and you can use Item2 to access the second model and so on.

in your controller you need to create a variable of type Tuple and then pass it to the view:

    public ActionResult Details(int id = 0)
    {
        Person person = db.Persons.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }
        var tuple = new Tuple<Person, Order>(person,new Order());

        return View(tuple);
    }

Another example : Multiple models in a view



回答3:

Another option which doesn\'t have the need to create a custom Model is to use a Tuple<>.

@model Tuple<Person,Order>

It\'s not as clean as creating a new class which contains both, as per Andi\'s answer, but it is viable.



回答4:

If you are a fan of having very flat models, just to support the view, you should create a model specific to this particular view...

public class EditViewModel
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

Many people use AutoMapper to map from their domain objects to their flat views.

The idea of the view model is that it just supports the view - nothing else. You have one per view to ensure that it only contains what is required for that view - not loads of properties that you want for other views.



回答5:

In fact there is a way to use two or more models on one view without wrapping them in a class that contains both.

Using Employee as an example model:

@model Employee

Is actually treated like.

@{ var Model = ViewBag.model as Employee; }

So the View(employee) method is setting your model to the ViewBag and then the ViewEngine is casting it.

This means that,

ViewBag.departments = GetListOfDepartments();
    return View(employee);

Can be used like,

            @model  Employee
        @{
                var DepartmentModel = ViewBag.departments as List<Department>;
        }

Essentially, you can use whatever is in your ViewBag as a \"Model\" because that\'s how it works anyway. I\'m not saying that this is architecturally ideal, but it is possible.



回答6:

ok, everyone is making sense and I took all the pieces and put them here to help newbies like myself that need beginning to end explanation.

You make your big class that holds 2 classes, as per @Andrew\'s answer.

public class teamBoards{
    public Boards Boards{get; set;}
    public Team Team{get; set;}
}

Then in your controller you fill the 2 models. Sometimes you only need to fill one. Then in the return, you reference the big model and it will take the 2 inside with it to the View.

            TeamBoards teamBoards = new TeamBoards();


        teamBoards.Boards = (from b in db.Boards
                               where b.TeamId == id
                               select b).ToList();
        teamBoards.Team = (from t in db.Teams
                              where t.TeamId == id
                          select t).FirstOrDefault();

 return View(teamBoards);

At the top of the View

@model yourNamespace.Models.teamBoards

Then load your inputs or displays referencing the big Models contents:

 @Html.EditorFor(m => Model.Board.yourField)
 @Html.ValidationMessageFor(m => Model.Board.yourField, \"\", new { @class = \"text-danger-yellow\" })

 @Html.EditorFor(m => Model.Team.yourField)
 @Html.ValidationMessageFor(m => Model.Team.yourField, \"\", new { @class = \"text-danger-yellow\" })

And. . . .back at the ranch, when the Post comes in, reference the Big Class:

 public ActionResult ContactNewspaper(teamBoards teamboards)

and make use of what the model(s) returned:

string yourVariable = teamboards.Team.yourField;

Probably have some DataAnnotation Validation stuff in the class and probably put if(ModelState.IsValid) at the top of the save/edit block. . .



回答7:

Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.

Personally I would just add them into one model but thats the way I do it:

public class xViewModel
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

@model project.Models.Home.xViewModel

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x => x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}


回答8:

You can use the presentation pattern http://martinfowler.com/eaaDev/PresentationModel.html

This presentation \"View\" model can contain both Person and Order, this new
class can be the model your view references.



回答9:

Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.



回答10:

you can\'t declare two model on one view, try to use Html.Action(\"Person\", \"[YourController]\") & Html.Action(\"Order\", \"[YourController]\").

Good luck.



回答11:

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag\'s value or data

List<tblproject> Plist = new List<tblproject>();
            Plist = ps.getmanagerproject(c, id);

            ViewBag.projectList = Plist.Select(x => new SelectListItem
            {
                Value = x.ProjectId.ToString(),
                Text = x.Title
            });

and in view tbltask and projectlist are my two diff models

@{

IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List