ASP.NET MVC Html.DropDownList SelectedValue [英] ASP.NET MVC Html.DropDownList SelectedValue

查看:39
本文介绍了ASP.NET MVC Html.DropDownList SelectedValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这是 RC1,然后升级到 RC2,但没有解决问题.

I have tried this is RC1 and then upgraded to RC2 which did not resolve the issue.

// in my controller
ViewData["UserId"] = new SelectList(
    users, 
    "UserId", 
    "DisplayName", 
    selectedUserId.Value); // this has a value

结果:在对象上设置了 SelectedValue 属性

result: the SelectedValue property is set on the object

// in my view
<%=Html.DropDownList("UserId", (SelectList)ViewData["UserId"])%>

result:所有预期的选项都呈现给客户端,但没有设置 selected 属性.SelectedValue 中的项存在于列表中,但列表中的第一项始终默认为选中.

result: all expected options are rendered to the client, but the selected attribute is not set. The item in SelectedValue exists within the list, but the first item in the list is always defaulted to selected.

我该怎么做?

更新感谢 John Feminella 的回复,我发现了问题所在.UserId"是我的视图强类型化的模型中的一个属性.当 Html.DropDownList("UserId" 更改为除 "UserId" 以外的任何其他名称时,所选值将正确呈现.

Update Thanks to John Feminella's reply I found out what the issue is. "UserId" is a property in the Model my View is strongly typed to. When Html.DropDownList("UserId" is changed to any other name but "UserId", the selected value is rendered correctly.

尽管如此,这会导致值未绑定到模型.

This results in the value not being bound to the model though.

推荐答案

我是这样解决这个问题的:

This is how I fixed this problem:

我有以下几点:

控制器:

ViewData["DealerTypes"] = Helper.SetSelectedValue(listOfValues, selectedValue) ;

查看

<%=Html.DropDownList("DealerTypes", ViewData["DealerTypes"] as SelectList)%>

更改如下:

查看

<%=Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList)%>

看起来 DropDown 的名称不能与 ViewData 名称相同:S 很奇怪,但它有效.

It appears that the DropDown must not have the same name has the ViewData name :S weird but it worked.

这篇关于ASP.NET MVC Html.DropDownList SelectedValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆