关于这个问题,我已经讨论过所有其他问题了。尝试张贴解决方案数十次,没有工作。
我有两门课:
public class Player
{
public int Id { get; set; }
[MinLength(1)]
public string Name { get; set; }
[MinLength(4)]
public string LastName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
public virtual Club Club { get; set; }
}和
public class Club
{
public int Id { get; set; }
[StringLength(30, MinimumLength = 3)]
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime Founded { get; set; }
public virtual ICollection<Player> Players { get; set; }
public override string ToString() {
return Name;
}
}在创建Player的操作方法中,我有:
// GET: /Players/Create
public ActionResult Create() {
//SelectList selectList = new SelectList(db.Clubs, "Id", "Name");
ViewBag.Clubs = new SelectList(db.Clubs, "Id", "Name");
return View();
}
// POST: /Players/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,LastName,Birthdate,Club")] Player player) {
if (ModelState.IsValid) {
db.Players.Add(player);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(player);
}在我尝试的表格中,我有下拉列表来选择球员所在的俱乐部:
<div class="form-group">
@Html.LabelFor(model => model.Club, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(player => player.Club, (SelectList)ViewBag.Clubs)
@Html.ValidationMessageFor(model => model.Club)
</div>
</div>下拉列表正确地呈现为,但当我接受表单时,会看到黄色的死亡屏幕,上面写着:There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Club'.
下拉列表看起来像这。
发布于 2016-06-01 10:32:15
ViewData只存在于当前响应中。当您从Create的POST重载返回时,没有什么可以填充ViewData。
在这些情况下,通常的模式是,从POST动作重定向到GET动作。这样可以避免重复代码,并确保刷新页面的用户不会再次发布前面的值。
https://stackoverflow.com/questions/37566032
复制相似问题