2010-06-09 152 views
9

我有一個表單發佈到MVC操作。我想從操作中的FormCollection中拉出選定的下拉列表項。我該怎麼做?從MVC中的FormCollection獲取選定的下拉列表值

我的HTML表單:

<% using (Html.BeginForm()) 
    {%> 
    <select name="Content List"> 
    <% foreach (String name in (ViewData["names"] as IQueryable<String>)) { %> 
      <option value="<%= name %>"><%= name%></option> 
    <% } %> 
    </select> 
    <p><input type="submit" value="Save" /></p> 
<% } %> 

我的行動:

回答

10

開始通過給您select標籤的有效name。有效的名稱不能包含空格。

<select name="contentList"> 

,然後取出從表單參數集合選定值:

var value = collection["contentList"]; 

甚至更​​好:不使用任何集合,使用具有相同的名稱作爲名稱的動作參數你的選擇,並保留默認的模型粘結劑填充它:

[HttpPost] 
public ActionResult Index(string contentList) 
{ 
    // contentList will contain the selected value 
    return RedirectToAction("Details", contentList); 
} 
+0

哦,快點!謝謝,那就是訣竅。我嘗試了兩種方法,但我喜歡你如何使用動作參數。 – 2010-06-09 10:58:15

相關問題