これは私がそれを行う方法です、あなたが2つのモデルを持っているとしましょうTeam and Player
:
Player.cs
public class Player
{
[HiddenInput(DisplayValue = false)]
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[ForeignKey("Team")]
[Display(Name = "Team")]
public int TeamId { get; set; }
[Display(Name = "First name")]
public string FirstName { get; set; }
[Display(Name = "Last name")]
public string LastName { get; set; }
public virtual Team Team { get; set; }
}
Team.cs
public class Team
{
[Key]
[HiddenInput(DisplayValue = false)]
public int TeamId { get; set; }
[Display(Name = "Full Name:")]
public string Name { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
次に、PlayerControllerで:
注:プレーヤーを作成するには、チームが存在する必要があります
private void PopulateTeamsDropDownList(object selectedTeams = null)
{
var teamsQuery = from d in _dataSource.Teams
orderby d.Name
select d;
ViewBag.TeamID = new SelectList(teamsQuery, "TeamId", "Name", selectedTeams);
}
[HttpGet]
public ActionResult Create()
{
PopulateTeamsDropDownList();
return View();
}
[HttpPost]
public ActionResult Create(Player model)
{
if (ModelState.IsValid)
{
using (EFootballDb db = new EFootballDb())
{
try
{
var player = new Player
{
FirstName = model.FirstName,
LastName = model.LastName
};
db.Players.Add(player);
db.SaveChanges();
return RedirectToAction("About", "Home");
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
}
PopulateTeamsDropDownList(model.TeamId);
return View(model);
}
そして最後に、Playerのビューの作成は次のようになります。
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Player</legend>
<div class="editor-label">
@Html.LabelFor(model => model.TeamId, "Pick Your Team")
</div>
<div class="editor-field">
@Html.DropDownList("TeamId", String.Empty)
@Html.ValidationMessageFor(model => model.TeamId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}