2012-10-09 52 views
0

我使用MVC 3在ASP.Net我的web應用程序是設計視圖模型和ViewModel builder選擇的數值如何顯示在編輯視圖一個DropDownList。從數據庫

我使用Builder類來填充ViewModel中的一些數據。在我的情況下,我有一個創建視圖DropDownList,與此代碼工作正常。我的問題是試圖創建一個編輯視圖時,我收到此錯誤:

{"The ViewData item that has the key 'CandidateId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'."} 

我的想法這將是填充一個DropDownList的一些價值,但已經預先選擇一個作爲DATABSE記錄。

那麼如何在編輯視圖中顯示DropDownList並從DataBase中選擇一個值?

VIEW

<div class="editor-label"> 
     @Html.LabelFor(model => model.CandidateId) 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(x => x.CandidateId, Model.CandidatesList, "None") 
    </div> 

視圖模型

public Nullable<int> CandidateId { get; set; } 
    public IEnumerable<SelectListItem> CandidatesList; 

視圖模型BUILDER

// We are creating the SelectListItem to be added to the ViewModel 
     eventEditVM.CandidatesList = serviceCandidate.GetCandidates().Select(x => new SelectListItem 
      { 
       Text = x.Nominative, 
       Value = x.CandidateId.ToString() 
      }); 

回答

1

原因這個錯誤是因爲你的[HttpPost]行動你忘了重新填充的CandidatesList財產數據庫中的視圖模型。

[HttpPost] 
public ActionResult Edit(EventEditVM model) 
{ 
    if (ModelState.IsValid) 
    { 
     // the model is valid => do some processing here and redirect 
     // you don't need to repopulate the CandidatesList property in 
     // this case because we are redirecting away 
     return RedirectToAction("Success"); 
    } 

    // there was a validation error => 
    // we need to repopulate the `CandidatesList` property on the view model 
    // the same way we did in the GET action before passing this model 
    // back to the view 
    model.CandidatesList = serviceCandidate 
     .GetCandidates() 
     .Select(x => new SelectListItem 
     { 
      Text = x.Nominative, 
      Value = x.CandidateId.ToString() 
     }); 

    return View(model); 
} 

不要忘記,當您提交表單時,只有選定的下拉列表值被髮送到服務器。該CandidatesList集合屬性將是你的POST控制器動作內空,因爲它的值永遠不會發送。所以如果你打算重新顯示相同的視圖,你需要初始化這個屬性,因爲你的視圖依賴於它。

+0

感謝Darin,你真的幫我解決這個問題!非常感謝您的時間! – GibboK