我尝试使用下面的视图模型无法获取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