2011-11-17 50 views
2

獲得價值。當我有這樣一個DropDownList是相關型號的觀點,即不相關的模型

@Html.DropDownListFor(model => model.Group.Name, selectList)

我可以檢索的控制器值如下:

string SelectedGroupName = collection.GetValue("Group.Name").AttemptedValue; 

但現在我有一個DropDownList是不相關的模型,但我需要的是價值,這是我的新下拉:

@Html.DropDownList("DDName", selectList) 

如何檢索控制器中選定的值?是否有任何隱藏的領域或其他東西來將視圖傳遞給控制器​​?

編輯

這是我的看法:

@model PhoneBook.Models.Numbers 
@{ 
ViewBag.Title = "Delete"; 
} 
<h2> 
    Move And Delete</h2> 
<fieldset> 
    <legend>Label of Numbers</legend> 
<div class="display-label"> 
     Delete Label And Move All Numbers with: @Html.DisplayFor(model => 
model.Title)</div> 
    <div class="display-field"> 
     To @Html.DropDownList("DDName", selectlist) 
    </div> 
</fieldset> 
@using (Html.BeginForm()) { 
    <p> 
    <input type="submit" value="Move Numbers And Delete Label" name="MDbtn" /> 
    </p> 
} 

這是我的控制器:

[HttpPost] 
    public ActionResult Delete(int id, FormCollection collection) { 
var result = Request["DDName"]; 

//Use result 

return RedirectToAction("Index"); 
} 

,但結果設置爲null,爲什麼呢?

+0

請求[「DDName」] –

+0

@amit_g:那不行,我編輯問題並添加一些代碼並測試你的方式,請看。 – Saeid

回答

2

我想這一定是工作傳遞值:

[HttpPost] 
    public ActionResult Delete(int id, FormCollection collection) 
    { 
     var dd = collection.GetValue("DDName"); 
      ..... 
    } 
0

我認爲你需要做的就是

您認爲:

@using (Html.BeginForm()) {<fieldset>以上,所以@Html.DropDownList("DDName", selectlist)是裏面。

在你的控制器:

public ActionResult Delete(int id, FormCollection collection, string DDName) 
{ [...] } 

而且我相當肯定MVC3會自動地給你選擇的值作爲參數傳遞給控制器​​。

如果不行,請在您的控制器中嘗試object DDName

+0

我嘗試兩種方式,但不工作,U檢索只是空值。 – Saeid

0

想想DDL必須是在你的形式,如果你想通過形式收集

0

你的問題是,你的下拉列表不包含在您的視圖中的表單中。

你必須把它BeginForm後:

@using (Html.BeginForm()) { 
    <div class="display-field"> 
    To @Html.DropDownList("DDName", selectlist) 
    </div> 

    <p> 
    <input type="submit" value="Move Numbers And Delete Label" name="MDbtn" /> 
    </p> 
} 

然後你可以使用的FormCollection或指定的參數。默認的模型綁定器將使用這兩種方法的工作:

ActionResult Action (FormCollection collection, string DDName) 

可以輕鬆地檢查這些問題與fiddler