Two models in one view in ASP MVC 3

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

    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. . .

提交回复
热议问题