Two models in one view in ASP MVC 3

后端 未结 12 2048
日久生厌
日久生厌 2020-11-22 13:55

I have 2 models:

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


        
12条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 14:36

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

    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.

提交回复
热议问题