使用我的ViewModel无法获得ASP.Net MVC Edit Action的价值

时间:2013-05-28 22:31:05

标签: asp.net-mvc-4

我正在尝试使用以下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);
}

除政府客户外,所有价值都会更新。为什么会这样?

2 个答案:

答案 0 :(得分:1)

projectViewModel.Project.GovernmentClient = 
       db.GovernmentClients.Find(projectViewModel.SelectedGovernmentClientId);

您正在从数据库中检索值并将其状态设置为已修改。但是,根本没有任何修改。

答案 1 :(得分:1)

经过一整天的游戏,我想我可能已经解决了它

我将以下内容添加到Project模型

[ForeignKey("GovernmentClient")]
public int GovernmentClient_ID { get; set; }

为了呈现下拉列表,我使用了这个

@Html.DropDownListFor(model => model.Project.GovernmentClient_ID, Model.GovernmentClients)

要生成GovernmentClients列表,我使用了以下方法

private IEnumerable<SelectListItem> GetGovernmentClientsList(int selectedItem = -1)
{
    var defaultItem = Enumerable.Repeat(new SelectListItem
    {
        Value = "-1",
        Text = " - Select a government client - ",
        Selected = (selectedItem == -1)
    }, count: 1);
    var clients = db.GovernmentClients.ToList().Select(x => new SelectListItem
    {
        Value = x.ID.ToString(),
        Text = x.ClientName,
        Selected = (selectedItem == -1) ? false : (x.ID == selectedItem)
    });
    return defaultItem.Concat(clients);
}

总的来说,我对此很满意,因为我并没有硬编码任何属性名称,我知道这些名称会回来咬我。