MVC下拉列表值未设置 [英] MVC Dropdown list value not being set

查看:98
本文介绍了MVC下拉列表值未设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,我缺少明显的东西,但是这是推动我疯了!如果我指定的HTML选项,我的DropDownList的值不设置。

I'm sure I am missing something obvious, but this is driving me nuts! If I specify html options, the value of my dropdownlist doesn't set.

在我的控制器,我检索选项我的DropDownList有:

In my controller, I retrieve the options for my dropdownlist with:

ViewData["Coordinator"] = new SelectList(userRepository.GetIdUserList(1), 
                          "ID",    "Signature",edCenter.Coordinator);

在我看来,我填充DropDownList的:

In my view I populate the dropdownlist with:


Html.DropDownList("Coordinator",(IEnumerable) ViewData["Coordinator"],
                   new {style="width:175px"})

的下拉值完全填充,但没有选择该列表的值

The dropdown values are populated perfectly, but the value of the list isn't selected.

不过,如果我只是用:

Html.DropDownList("Coordinator");

一切工作正常。

Everything works fine.

这是怎么回事?错

推荐答案

我是用一个类似的问题昨天挣扎,所以如果你仍然得到同样的结果还有一个要考虑的。 DropDownList中有时会忽略你的SelectList的设定值,这很烦人,但它的作用是试图通过使用字段名作为一键搞定从ModelState中,ViewData的型号和所选择的值。
在你的情况你是存储ViewData的列表[协调员],键具有相同的名称作为下拉。试试这个:

I was struggling with a similar problem yesterday so if you are still getting the same result there is one more thing to consider. The DropDownList sometimes ignores the selected value of your SelectList, it's annoying but what it does is try to get the selected value from the ModelState, ViewData and Model by using the field name as a key. In your case you are storing the list in ViewData["Coordinator"], the key has the same name as the DropDown. Try this:

ViewData["CoordinatorList"] = new SelectList(userRepository.GetIdUserList(1), 
                          "ID",    "Signature",edCenter.Coordinator);

ViewData["Coordinator"] = dCenter.Coordinator;

然后在视图:

    <%=Html.DropDownList("Coordinator",((SelectList)ViewData["CoordinatorList"]).AsEnumerable(),
 new {style="width:175px"}) %>

如果你想看看发生了什么窗帘开反射的背后(或获得MVC源)和浏览这个方法:
System.Web.Mvc.Html.SelectExtensions.SelectInternal()

If you want to see what's going on behind the curtains open reflector (or get the MVC source) and browse this method: System.Web.Mvc.Html.SelectExtensions.SelectInternal()

这篇关于MVC下拉列表值未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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