我有一些SelectList和DropDownList的問題。 ICH有兩種型號(TimeRecord有一個導航屬性項目):ASP NET MVC 5 SeletList DropDownList
public class Project
{
public int ProjectId { get; set; }
[Required]
public string ProjectName { get; set; }
}
和
public class TimeRecord
{
public int TimeRecordId { get; set; }
public int ProjectId { get; set; }
public string Description { get; set; }
public Project TmRecProject { get; set; }
}
在我創建行動方法控制選擇列表的是路過ViewBag到視圖(到現在都是正確的工作)
public ActionResult Create()
{
ViewBag.ProjectId = new SelectList(db.Projects, "ProjectId", "ProjectName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TimeRecord timeRecord)
{
if (ModelState.IsValid)
{
db.TimeRecords.Add(timeRecord);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(timeRecord);
}
這裏查看:
@model SelectListDropDownTest.Models.TimeRecord
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TimeRecord</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.TmRecProject.ProjectId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ProjectId", null, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
在創建視圖中,我可以從DropDownList中選擇一個項目。我的問題是,當我將模型「TimeRecord」傳遞迴控制器時,項目「TmRecProject」始終爲空。
解決此問題的最佳方法是什麼?
您需要綁定「ProjectId」(而不是'TmRecProject'),這是您的代碼正在執行的操作(雖然很糟糕) - 它將保存數據時更新的「ProjectId」的值。你的實現意味着你不會得到客戶端驗證,並且'SelectList'的名字需要和你綁定的屬性不同,以便在視圖中它的'@ Html.DropDownListFor(m => m.ProjectId,(SelectList )ViewBag.ProjectList,new {@class =「form-control」})'無論如何,您的編輯數據總是使用視圖模型 –