2013-07-12 79 views
0

客戶可以查看他們的客戶詳細信息頁面,他們可以更改預先記錄的交付運行(如果他們也希望的話)我有一個包含城市交貨運行的下拉列表:DropDown不顯示以前選擇和保存的內容

<div class="editor-label">@Html.DropDownListFor(model => model.DeliveryRunList, Model.DeliveryRunList)</div> 

加載客戶配置文件時,在下拉菜單中顯示正確的城鎮(從註冊時他們之前選擇的DB中讀取)。

但是,如果他們改變城鎮並保存它,用戶將返回到主頁,並將新選擇的路徑保存到數據庫。但是,如果用戶返回到客戶資料頁面,則下拉菜單顯示先前選擇的城鎮,而不是之前選擇的新城鎮並將其保存到數據庫。它是否存儲在緩存的某處。

爲什麼它不更新到實際在數據庫中?

代碼隱藏:

CustomerPart custPart = _custService.Get(custId); 

if (DeliveryRunList.HasValue) 
{ 
    custPart.DeliveryRun_Id = DeliveryRunList.Value; 
} 

_custService.Update(custPart); 

感謝

+0

聽起來像是你只需要在加載頁面時填充它。獲取客戶城鎮並設置下拉列表的選定索引=城鎮值(假設您對城鎮ID /城鎮文本中的數據和文本字段有約束力) – DGibbs

+0

您是否調試過該語句以確保更新實際發生。 。我認爲,如果你的模型綁定到下拉列表的現有值,那麼它將始終有一個值... – Rikon

+1

請發佈定義DeliveryRunList的代碼。 – ataravati

回答

0

我想model是CustomerPart實例,並且您已經或多或少地這樣定義它。

public class CustomerPart 
{ 
    public int DeliveryRun_Id {get; set;} 
    public SelectList(or some IEnumerable) DeliveryRun_Id 
} 

我覺得你的代碼沒有更新數據庫,因爲你使用了錯誤的屬性。第一個lambda表達式應該是model => model.TheAttributeYouWantToUpdate,在這種情況下是DeliveryRun_Id

所以它應該是:

@Html.DropDownListFor(model => model.DeliveryRun_Id, Model.DeliveryRunList) 

而不是

它也不是不清楚的地方是這個代碼在控制器內部:

CustomerPart custPart = _custService.Get(custId); 

if (DeliveryRunList.HasValue) 
{ 
    custPart.DeliveryRun_Id = DeliveryRunList.Value; 
} 

_custService.Update(custPart); 

這樣做的一種常見方式是有兩個同名的方法進行編輯,一個用於HttpGet,一個用於HttpPost,並使用@Html.BeginForm()在剃刀視圖中進行更新,而不是更新控制器中的信息。

例子:

 public ActionResult Edit(int id = 0) { 
      InvestmentFund Fund = InvestmentFundData.GetFund(id); 
      return Fund == null ? (ActionResult)HttpNotFound() : View(Fund); 
     } 

     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Edit(InvestmentFund Fund) 
     { 
      if (ModelState.IsValid) 
      { 
       InvestmentFundData.Update(Fund); 
       return RedirectToAction("List"); 
      } 
      return View(Fund); 
     } 

在查看

@using (Html.BeginForm()) { 
     @Html.AntiForgeryToken() 
     @Html.ValidationSummary(true) 

     @* For the attributes of your model *@ 
     @Html.LabelFor ... 
     @Html.EditorFor ... 
     @Html.ValidationMessageFor ... 

     <input type="Submit"m value="Save"> 
    } 
+0

感謝您抽出時間給我一個詳細的回覆......這確實解決了最初的問題......現在當頁面加載時,正確的交付運行將顯示。然而,新的問題是:如果用戶試圖'保存'頁面,deliveryRunRecord.Id返回爲NULL,並拋出未設置爲對象的實例的對象引用....任何想法? – John

+0

我不知道deliveryRunRecord是什麼。你最好打開一個新的問題,並提供有關你的程序的更多細節。請參閱http://sscce.org/。 – octref