由于我是ASP.NET Core 2.0 MVC的新用户,我有一个小型的演示应用程序,我想添加一个新的Type Lineup实体,其模型中有一个类型为Player的ICollection。
所涉及的课程是
public class Lineup
{
public int LineupID { get; set; }
public int PlayerID { get; set; }
public ICollection<Player> Attendants { get; set; }
}
和
public class Player
{
public int PlayerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
我的创建阵容视图如下所示
<form asp-action="Create">
<div class="form-horizontal">
<h4>Lineup</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Attendants" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Attendants" class="form-control"
asp-items="ViewBag.Players" multiple="multiple">
</select>
</div>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
ViewBag.Players是LineupsController的一部分:
private void PopulatePlayersDropDownList(object selectedPlayer = null)
{
var playersQuery = from p in _context.Player
orderby p.Name
select p;
ViewBag.Players = new SelectList(playersQuery.AsNoTracking(), "PlayerID",
"Name", selectedPlayer);
}
到目前为止看起来是这样的:
但在我的Create方法
中public async Task<IActionResult> Create([Bind("Attendants")] Lineup lineup)
{
if (ModelState.IsValid)
{
_context.Add(lineup);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(lineup);
}
Lineup实体的Attendants计数为0,而不是上述示例中预期的2。这有什么不对?谢谢你的帮助。
答案 0 :(得分:4)
创建对象时需要实例化属性。否则,该属性是默认值,即public class Lineup
{
public int LineupID { get; set; }
public int PlayerID { get; set; }
public ICollection<Player> Attendants { get; set; } = new List<Player>();
}
:
"$(document).ready(function(){"
答案 1 :(得分:0)
将“创建”的方法签名更改为
public async Task Create(int [] PlayerIDs) { ... }