在Html.DropDownList可能的错误,选择的值不反映? [英] Possible bug in Html.DropDownList, selected values not reflecting?
问题描述
我知道这已经被问了几次过,但现有的解决方案看起来像黑客,而不是一个适当的模式。
I know this has been asked a few times before, but the existing solutions look like hacks rather than a proper pattern.
我有一个简单的下拉列表中。我试图用数据填充它,然后有一个项目pre选择。我成功举行的用数据部分填充它,但不能让我的preferred项目pre-选择。
I have a simple drop down list. I am trying to populate it with data and have a item pre selected. I am succeeding at the 'populate it with data part' but failing to get my preferred item pre-selected.
我使用的ASP.NET MVC 3 RC2。
I am using ASP.NET MVC 3 RC2.
重要code位:
{
// Bunch of code
CategoryOptions = new SelectList(categories, "Id", "Slug", article.Category.Id);
}
现在......在CategoryOptions被传递到HTML帮助像这样:
Now... the CategoryOptions is being passed to the Html helper like so:
@Html.DropDownListFor(a => a.Category, Model.CategoryOptions)
我看过的值被传递到辅助,并确认其中一个项目已经选定的值设置为true:
I have looked at the values being passed into the helper and have confirmed that one of the items has the selected value set to true:
然而,它不反映在HTML正由辅助产生的。没有一个...标签已经选定=选择属性。
However, it is not reflecting in the Html being generated by the helper. None of the ... tags have the selected="selected" attribute.
我用反射来检查codeA位,而这条线(SelectExtensions.SelectInternal)看起来冒险:
I used Reflector to examine the code a bit, and this line (SelectExtensions.SelectInternal) looks dicey:
item.Selected = (item.Value != null) ? set.Contains(item.Value) : set.Contains(item.Text);
我是不是做错了什么吗?或者是框架(ASP.NET MVC 3 RC2)这里有毛病。
Am I doing something wrong here? Or is the framework (ASP.NET MVC 3 RC2) at fault here.
推荐答案
好吧...我只是固定它。
Ok... I just fixed it.
我改变了我的身边视图模型使用类别塞的的CategoryId代替。所以,现在,我的看法是这样的:
I changed around my view model to use a CategoryId instead of a Category slug. So now, my view looks like:
@Html.DropDownListFor(a => a.CategoryId, Model.CategoryOptions, new { @class = "ask-category-field" })
我认为该模型值为选择(在此情况下,一个=> a.CategoryId)必须具有相同的类型选择的价值。 (当我得到更多的时间走了过来框架code,我将完善这一解释。)但到ASP.NET MVC开发者巧妙的编码确实:)帽子。
I think the model value being select (in this case, a => a.CategoryId) has to have the same type as the selected 'value.' (I will refine this explanation when I get more time to go over the framework code.) But clever coding indeed :) Hats of to ASP.NET MVC devs.
现在,它完美的期望,也保留了跨PRG生命周期的变化到所选择的项目。
Now, it works perfectly as expect and also retains changes to the selected item across a PRG lifecycle.
希望这可以帮助别人。
这篇关于在Html.DropDownList可能的错误,选择的值不反映?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!