有沒有簡單的方法,沒有手動循環數組中的所有項目,從一個下拉菜單的字符串數組轉換爲SelectList?將字符串[]轉換爲列表<SelectList>
回答
我假設您需要SelectList
或List<SelectListTiem>
而不是List<SelectList>
。 SelectList
具有a constructor,需要一個集合:
string[] = new [] { .. strings .. };
SelectList sl = new SelectList(strings);
,也可以投影到List<SelectListItem>
:
string[] = new [] { .. strings .. };
var sl = strings.Select(s => new SelectListItem {Value = s})
.ToList();
注意SelectList
實現IEnumerable<SelectListItem>
,所以如果你有類型的模型屬性IEnumerable<SelectListItem>
您可以創建一個SelectList
並將其分配給該屬性,而不是投影到List<SelectListItem>
。它在功能上是相同的,但代碼將會更清晰。
這一切都是假設我們正在談論的MVC,而不是Web窗體
二至d士丹利的答案,另一種解決方案:
string[] strings = new [] { ... strings ... };
var selectListItems = strings.Select(x => new SelectListItem() { Text = x, Value = x, Selected = x == "item 1" });
的SelectListItem
列表也可以用來填充的MVC下拉列表。
使用此方法,還可以在SelectListItem
上設置其他屬性,如顯示值。
我們不能使用SelectListItem
構造函數在IQueryable
上調用Select
,因爲LINQ會嘗試將其轉換爲SQL。除非有提供者,否則是不可能的,也不是我們想要實現的。
爲了始終確保我們可以像上面顯示的那樣列舉,我們需要強制EF或其他ORM將所有數據恢復。我們可以通過調用ToList()
之前爲此我們列舉與Select
:
var selectListItems = strings.ToList().Select(x => new SelectListItem() { Text = x, Value = x, Selected = x == "item 1" });
由於@BCdotWEB曾指出:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
的是,這個名單難免會投入構造。如果我沒記錯的話,在Razor視圖應該是這樣的:
@Html.DropDownListFor(x => x.SelectedString, new SelectList(x.Strings, "Value", "Text"))
哪裏x.SelectedString
是希望從下拉被放在選擇的值。 x.Strings
是selectListItems
我們在Controller
/Service
您需要在最後調用'.ToList()'來獲取'List'而不是'IEnumerable'。如果你不打算這麼做,永遠不會知道什麼時候懶惰的評估會咬你。 – 2015-02-24 15:08:41
'SelectListItem'沒有一個具有值的構造函數。您必須明確設置「Value」屬性。 – 2015-02-24 15:11:54
我會進行這些更改,謝謝 – 2015-02-24 15:14:31
創建我假設你可以使用SelectList Constructor,因爲它接受一個IEnumerable:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
,如果你談論的是ASP。淨web表單您可以使用此代碼
string[] stringArray= new []{"var1",...};
Dictionary<string,string> listItemSource=stringArray.ToDictionary(i => i, i =>i);
yourDropDownList.DataSource=listItemSource;
yourDropDownList.DataValueField = "value";
yourDropDownList.DataTextField = "key";
yourDropDownList.DataBind();
- 1. 將字符串轉換爲字列表?
- 2. 將字符串列表轉換爲字符串列表
- 3. 將列表轉換爲字符串 - TCL
- 4. 將字符串值轉換爲列表
- 5. 將Enumerable.Range轉換爲字符串列表
- 6. Java - 將字符串轉換爲列表
- 7. 將字符串轉換爲列表
- 8. 將字符串轉換爲列表
- 9. 將字符串轉換爲列表
- 10. 將列表轉換爲字符串
- 11. 將字符串轉換爲int64列表
- 12. 將字符串列表轉換爲xml
- 13. Linq將字符串轉換爲列表
- 14. 將列表轉換爲字符串
- 15. 將列表轉換爲字符串?
- 16. 將字符串列表轉換爲
- 17. 將字符串轉換爲列表
- 18. 將AppleScript列表轉換爲字符串
- 19. 轉換列表轉換爲字符串
- 20. 將字符串轉換爲列表<string>在一行中?
- 21. 將字符串數組轉換爲列表<string>
- 22. 如何將列表<object>轉換爲字符串數組
- 23. 將列表<DataRow>轉換爲字符串
- 24. 將列表<String>轉換爲Java中的字符串[]
- 25. dart:html - 將字符串從HttpRequest轉換爲列表<int>
- 26. 將字符串轉換爲列表<string>
- 27. 在Dart中將列表<int>轉換爲字符串?
- 28. 如何將列表<Class>轉換爲字符串?
- 29. 將json對象的字符串[]轉換爲列表<T>
- 30. 將字符串轉換爲<S3Uri>
一個'名單'實際上是一個2-d陣列(名單列表) - 你怎麼建議的1-d陣列轉換爲? –
2015-02-24 15:05:00
這是關於ASP.Net MVC的問題嗎? – Habib 2015-02-24 15:05:32
每個人的答案只是消失... – 2015-02-24 15:06:35