我嘗試使用下面的視圖模型無法獲取ASP.Net MVC編輯行動值得我的ViewModel
public class ProjectViewModel
{
public Project Project { get; set; } //bulk of the information
public int SelectedGovernmentClientId { get; set; } //selected ID for the dropdown
public IEnumerable<SelectListItem> GovernmentClients { get; set; } //dropdown values
}
這裏是我的項目類
public class Project
{
public int ID { get; set; }
public string Title { get; set; }
//omitting extra fields
public virtual GovernmentClient GovernmentClient { get; set; }
}
這裏,我有行動
[HttpPost]
public ActionResult Edit(ProjectViewModel projectViewModel)
{
if (ModelState.IsValid)
{
//i am getting the following from debugging
//projectViewModel.Project.GovernmentClient.Name is NULL
//projectViewModel.Project.GovernmentClient.ID is the correct ID from the dropdown
db.Entry(projectViewModel.Project).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(projectViewModel);
}
除政府客戶以外,所有的值都得到更新。這是爲什麼發生?
你調試了代碼嗎? 'projectViewModel.SelectedGovernmentClientId'的價值是什麼?從數據庫獲取值後,「projectViewModel.Project.GovernmentClient」的值是多少? – Kenneth
'projectViewModel.SelectedGovernmentClientId'返回下拉菜單中的選定值。 'projectViewModel.Project.GovernmentClient'開始爲空,但在賦值後包含正確的GovernmentClient對象 – PBG
實體是否附加到上下文? – Kenneth