1

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

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

4

2 回答 2

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

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

于 2013-05-29T00:04:29.767 回答
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);
}

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

于 2013-05-29T19:42:06.107 回答