2011-03-01 57 views
0

我有一系列我想讓用戶添加和編輯的DropDown。我從StackOverflow找到了一個助手擴展來構建一個動作圖像鏈接。ASP.NET MVC從DropDownList獲取Id(值)

@Html.DropDownListFor(model => model.Entry.ParadigmId, ((IEnumerable<Pylon.Models.Paradigm>)ViewBag.PossibleParadigms).Select(option => new SelectListItem { 
      Text = (option == null ? "None" : option.Name), 
      Value = option.ParadigmId.ToString(), 
      Selected = (Model != null) && (option.ParadigmId == Model.Entry.ParadigmId) 
     }), "Select") 

@Html.ActionImage("ParadigmEdit", new { id = ? }, "~/Content/Images/Edit_Icon.gif", "ParadigmEdit") 

我不知道如何在DropDownList中引用選中的id值,其中問號位於上面的代碼中。

回答

1

您不能使用服務器端代碼(HTML幫助程序代表的)從下拉列表中選擇值,因爲選擇是由客戶端上的用戶完成的。你的問題源於這樣一個事實,即你正試圖生成一個錨點,它應該發送一個只有客戶端已知的值。你只能使用javascript來做到這一點。或者另一種可能性是簡單地用一個形式與圖像提交按鈕:

@using (Html.BeginForm("ParadigmEdit", "ControllerName")) 
{ 
    @Html.DropDownListFor(
     model => model.Entry.ParadigmId, 
     // WARNING: this code definetely does not belong to a view 
     ((IEnumerable<Pylon.Models.Paradigm>)ViewBag.PossibleParadigms).Select(option => new SelectListItem { 
      Text = (option == null ? "None" : option.Name), 
      Value = option.ParadigmId.ToString(), 
      Selected = (Model != null) && (option.ParadigmId == Model.Entry.ParadigmId) 
     }), 
     "Select" 
    ) 
    <input type="image" alt="ParadigmEdit" src="@Url.Content("~/Content/Images/Edit_Icon.gif")" /> 
} 

,當然您將醜陋的代碼,它屬於(映射層或視圖模型)後,您的代碼將變成:

@using (Html.BeginForm("ParadigmEdit", "ControllerName")) 
{ 
    @Html.DropDownListFor(
     model => model.Entry.ParadigmId, 
     Model.ParadigmValues, 
     "Select" 
    ) 
    <input type="image" alt="ParadigmEdit" src="@Url.Content("~/Content/Images/Edit_Icon.gif")" /> 
} 
+0

重構到映射層或視圖模型的任何指針?那我怎麼把一個帶有兩個屬性id和name的Paradigm模型類轉換成Model.ParadigmValues? – CyberUnDead 2011-03-04 13:09:41

+1

@Cyber​​UnDead,我個人使用[AutoMapper](http://automapper.codeplex.com)在我的域模型和視圖模型之間進行轉換。 – 2011-03-04 13:11:26