2016-09-09 44 views
0

我想要改變SelectList構造函數中dropDownList的默認選擇,selectList構造函數允許第三個參數,它是一個表示SelectList的DataTextField值的字符串,但是當我嘗試以下任一操作:在選擇列表的DataTextField中設置默認值

new SelectList(new[] { 1, 2, 3, 4 }, Model.XXXX.xxxx, 3) 
new SelectList(new[] { 1, 2, 3, 4 }, Model.XXXX.xxxx, "3") 

我得到一個錯誤:

"The best overloaded method match has some invalid arguments"

什麼我不理解?在我看來,上面的第二行應該工作,因爲我給了它第三個字符串參數顯示在DataTextField中。

作爲未成年人subquestion,這是什麼語法

new[] { 1, 2, 3, 4 } 

是什麼意思?在new關鍵字對我來說是陌生的之後,我是C#和括號中的新手。

+0

您可以通過綁定到模型屬性來設置初始選定選項。如果你有一個屬性(比如說)Number,並將它的值設置爲3,那麼使用@Html.DropDownListFor(m => m.Number,new SelectList(new [] {1,2,3,4 }))'會選擇第三個選項。這就是模型綁定的工作原理。 –

回答

1
SelectList sl = new SelectList(new[]{ 
    new SelectListItem{ Text="one", Value="1"}, 
    new SelectListItem{ Text="two", Value="2"}, 
    new SelectListItem{ Text="three", Value="3"} 
}, "Text", "Value", "3"); 

要將另一個問題,

new[] { 1, 2, 3, 4 }

你基本上創建int數據類型的與它的元素爲1,2,3和4

+0

你是對的Richa,upvoting –

0

構造您正在使用的SelectList陣列

public SelectList(
    IEnumerable items, 
    string dataValueField, 
    string dataTextField 
) 

MSDN

當SelectList通過View呈現時,它只是HTML,因此您應該將匿名數組作爲字符串,dataValueField和dataTextField作爲字符串提供。 看在這方面

<select> 
 
     <option value="1">1</option> 
 
     <option value="2">2</option> 
 
     <option value="2">3</option> 
 
     <option value="2">4</option> 
 
    </select>

更改您的代碼如下

new SelectList(new[] { "1", "2", "3", "4" }, Model.XXXX.xxxx, "3") 

Model.XXXX.xxxx將其更改爲您的數據值字段。

new[] { 1, 2, 3, 4 } // anonymous type by using the new operator with an object initializer. here this anonymous array is int type. 

MSDN

希望它幫助。

1

其中一個重載選擇列表的構造方法是以下

SelectList(IEnumerable, String, String); 

的IEnumerable - >數據值字段

字符串 - - >數據>爲列表

字符串項目文本字段

您IEnumerable是new[] { 1, 2, 3, 4 }它基本上是一個整數數組,其元素爲1,2,3和4。

數據值字段是您的模型,文本字段是「3」。

如果你想從你的模型之一創建一個選擇列表,我建議你做以下

new SelectList(Model, "Data Value field", "Data text field"); 

例如: 如果你有一個學生模型(Std_ID,Std_Name),和您需要一個選擇列表來顯示學生姓名並保存其ID的值

new SelectList(Model, "Std_ID", "Std_Name");