Two models in one view in ASP MVC 3

后端 未结 12 1901
日久生厌
日久生厌 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:58

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

    @model Tuple
    

    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 Tuple 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,new Order());
    
            return View(tuple);
        }
    

    Another example : Multiple models in a view

提交回复
热议问题