2013-05-28 51 views
1

我嘗試使用下面的視圖模型無法獲取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); 
} 

除政府客戶以外,所有的值都得到更新。這是爲什麼發生?

+1

你調試了代碼嗎? 'projectViewModel.SelectedGovernmentClientId'的價值是什麼?從數據庫獲取值後,「projectViewModel.Project.GovernmentClient」的值是多少? – Kenneth

+0

'projectViewModel.SelectedGovernmentClientId'返回下拉菜單中的選定值。 'projectViewModel.Project.GovernmentClient'開始爲空,但在賦值後包含正確的GovernmentClient對象 – PBG

+1

實體是否附加到上下文? – Kenneth

回答

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); 
} 

總的來說,我對此感到滿意,因爲我不硬編碼任何屬性名稱,我知道它會回來咬我。

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

您正在從數據庫中檢索值並將其狀態設置爲已修改。但是,根本沒有修改。

+0

我的錯誤是,我添加了該行以嘗試修復它。代碼修改。 – PBG

相關問題