mavera
mavera

Reputation: 3241

Working with two models in one view with mvc 3

Let's imagine we have two models:

Teams: Id, Name
Player: Id, Name, TeamId

I want to save a team and player collection of this team on one view. So there must be these element in my view:

In this situation, we should work with two models on one view. Especially, I want to see how add button scenario should be.

Can anyone help about that?

Upvotes: 2

Views: 2373

Answers (1)

tvanfosson
tvanfosson

Reputation: 532445

You would typically use a view model for this that decomposes into (maps to) your entity models. The model might look like:

 public class MeamWithPlayersViewModel
 {
      public long ID { get; set; }  // this ought to match the id parameter on the post
      public string Name { get; set; }
      public TeamPlayer[] Players { get; set; }
 }

 public class TeamPlayer
 {
      public long PlayerID { get; set; }
      public string Name { get; set; }
 }

In your view -- assuming you add players for a specific team --

 @using (Html.BeginForm())
 {
       <p>Current Players</p>
       @for (int i = 0; i < Model.Players.Length; ++i)
       {
             <p>Model.Players[i].Name
             @Html.HiddenFor( model => model.Players[i].PlayerID )
             </p>
       }
       <button class="add-player">Add Player</button>
       <button class="save-button">Save</button>
 }

Then using some javascript with AJAX you'd implement the ability to add a new player from a list retrieved via AJAX. In the callback from the add player code (tied to the button), you'd add the name and another hidden field with the player's id <input type="hidden" name="Players[n].PlayerID" value="_some_id_" />, where n is the next number in the sequence. You might be able to omit n depending on your exact functionality.

Upvotes: 4

Related Questions