2017-01-11 20 views
0

我遇到了使用SelectList和Html.DropDownList的问题,我一直无法通过查看以前问题的答案来解决问题。如何正确使用Html.DropDownList与SelectList?

我有一个查看下面的代码:

Dim myItems As New Collection 
Dim thisItem As SelectListItem 

For Each responsibility In Model.Responsibilities.EBS_Resonsibility 

    thisItem = New SelectListItem 
    thisItem.Text = responsibility.RESPONSIBILITY_NAME 
    thisItem.Value = responsibility.RESPONSIBILITY_ID 
    myItems.Add(thisItem) 
Next 

从我的模型考虑每个项目,把它变成一个SelectListItem,并将其添加到集合。

然后,我把它转换成一个的SelectList:

Dim myRoles As New SelectList(myRoleItems, "Value", "Text") 

,创造我Html.DropDownList:

@Html.DropDownList("RoleList", myRoles, "Select Role") 

最后处理:

<a href="@Url.Action("RoleHandler", "Account", New With {.RESPONSIBILITY_ID = myRoles.SelectedValue})">Search Buildings</a> 

的问题是,什么正在通过。我知道我的最后一行与我的SelectList是正确的,因为如果我添加一个参数来选择列表的结束为了selectedValue,它会传递参数,像这样:

Dim myRoles As New SelectList(myRoleItems, "Value", "Text", 905) 

在这种情况下,905获得通过。所以,我相当肯定,我在DropDownList中访问我的SelectList中的值时出错。项目的名称虽然在DDL中正确显示,所以我不确定哪里出错了。

任何帮助将不胜感激,谢谢!

+0

边注:'myRoleItems'是'的IEnumerable '(这是通过用'的DropDownList()'方法需要使用新'的SelectList(myRoleItems“。值“,”文本“)​​从第一个创建另一个相同的'IEnumerable '是毫无意义的。 –

回答

0

您拥有的锚标记的代码有一些C#代码,它会在服务器上执行。由于用户可以将所选的下拉选项更改为客户端的其他内容,因此您应该使用客户端JavaScript进行处理。

因此,将链接的href值设置为action方法的基本url(不包含路由值)并为其指定一个id,我们将使用它来连接某些客户端行为。

@:<a id="myLink" href="@Url.Action("RoleHandler","Account")">Search Building</a> 

现在有一些JavaScript代码来听click事件此链接,请从下拉列表中选择选项,并用它来建立新的URL。

@section scripts 
    <script> 
    $(function() { 

     $("#myLink").click(function (e) { 
      e.preventDefault(); 
      var url = $(this).attr("href"); 
      url = url + "?RESPONSIBILITY_ID ="+$("#RoleList").val(); 
      window.location.href = url; 
     }); 

    }); 
</script> 
End Section 

而且,你并不真的需要创建一个新的SelectList对象,你可以SelectListItem列表传递给您的DropDownList的辅助方法。

Dim list = New List(Of SelectListItem)() From { 
    New SelectListItem() With { 
         .Value = "a", 
         .Text = "a" 
    }, 
    New SelectListItem() With { 
         .Value = "b", 
         .Text = "b" 
    } 
} 

@Html.DropDownList("RoleList", list, "Select Role")