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:
- input for team name
- input for player name
- add button to add player name from input to collection
- a list开发者_开发知识库 of added players
- save button to save the team and player's collection.
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?
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.
精彩评论