2013-07-03 45 views
1

MVC3 DropdownListFor模型屬性不綁定到選定值 這是我的看法DROPDOWNLIST不結合模擬財產MVC3

@{var items = new List<SelectListItem>(){ 
          new SelectListItem {Text = "2", Value = "2", Selected = true}, 
          new SelectListItem {Text = "3", Value = "3", Selected = false}, 
          new SelectListItem {Text = "4", Value = "4", Selected = false}, 
          new SelectListItem {Text = "5", Value = "5", Selected = false} 
         }; 

     } 
@Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text")) 

InvoiceModel有一個名爲InvoiceItem類屬性進一步爲int類型的屬性Count。 count屬性始終爲0,並未更新爲從下拉列表中選擇的值。

請幫忙我已經在此花了數小時。謝謝。


謝謝你的回覆。但我仍然有這個問題。

我用 @ Html.DropDownListFor(X => x.InvoiceItem.Count,新的SelectList(項目時, 「值」, 「文本」,2))

也嘗試@ Html.DropDownListFor(X = > x.InvoiceItem.Count,new SelectList(items,「value」,「text」,「2」))

Count屬性總是0.我在這裏丟失了什麼。

+0

我想確保我的問題很清楚,下拉列表的默認值爲2,但是當我保存它時,與下拉列表關聯的模型屬性未設置爲2.它始終爲0。 – user2548196

回答

1

用途:

new SelectList(items, "value", "text", selectedvalue); 

例:

@{var items = new List<SelectListItem>(){ 
           new SelectListItem {Text = "2", Value = "2"}, 
           new SelectListItem {Text = "3", Value = "3"}, 
           new SelectListItem {Text = "4", Value = "4"}, 
           new SelectListItem {Text = "5", Value = "5"} 
          }; 

      } 
    @Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text", 2)) 
+0

請進一步建議。我被困在這裏。 – user2548196

0

這是因爲Model.InvoiceItem.Count(在DropDownListFor第一個參數)的電流值在您的SelectList中重寫選擇的值。

正是這樣,您的視圖模型的當前值可用於設置模型錯誤後的值。

解決這一問題已經張貼Cyber​​drew,你必須使用的SelectList構造函數的第三個參數,其表示默認選擇的值:

@Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text", 2)) 
+1

我想確保我的問題很清楚,下拉列表中選擇了默認值2,但是當我保存它時,與下拉列表關聯的模型屬性未設置爲2.它始終爲0。 – user2548196

0

我想通了這個問題。我沒有在保存按鈕點擊事件中將下拉列表發佈到控制器。

2

也許你的問題和我的一樣。請檢查x.InvoiceItem.Count是屬性還是字段。如果它是一個字段,發佈數據將不會綁定到它。

我的模型

public class SearchReportObject 
{ 
    public string report_type; 
} 

在CSHTML

@Html.DropDownListFor(model => model.report_type, new SelectList(new List<Object>{new { value = "0" , text = "Red" },new { value = "1" , text = "Blue" },new { value = "2" , text = "Green"}} , "value", "text")) 

在後的形式,report_type總有null值。但是當我將report_type從字段更改爲像這樣的屬性時:

public class SearchReportObject 
{ 
    public string report_type{ set; get; } 
} 

它工作正常。