2011-03-01 68 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