SelectListItem中的选定属性永远不起作用(DropDownListFor) [英] Selected property in SelectListItem never works (DropDownListFor)

查看:195
本文介绍了SelectListItem中的选定属性永远不起作用(DropDownListFor)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择DropDownList的值时遇到问题.我一直在阅读所有类似的文章,但找不到解决方法.

I have problems when selecting a value of a DropDownList. I've been reading all the similar posts and I can't get a solution.

实际方法对我来说似乎非常好,因为我可以检查SelectList内的字段:

The actual approach seemed very good to me, because I can inspect the fields that will be inside the SelectList:

var selectList = new List<SelectListItem>(
    from variable in someKindOfCollection
    select new SelectListItem
        {
            Selected = variable.Property == selection,
            Text = variable.Property,
            Value = variable.Property
        });

据说,这可以完全控制我.创建完selectList之后,我可以使用调试器检查变量.一切正常,其中之一已标记为已选择"属性.

Supposedly, this gives me total control. After the selectList has been built I can inspect the variables with the debugger. Everything is OK and one of them has the "Selected" attribute marked.

然后我使用DropDownListFor以便在视图上显示:

Then I use DropDownListFor in order to show on the view:

@Html.DropDownListFor(
    g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })

但这是行不通的,永远不会...渲染"下拉列表,但未选择任何内容.

But It doesn't work, never... "Renders" the dropdown, but nothing is selected.

非常感谢:)

新示例 首先,我要道歉.我一直在隐藏信息,当然完全是无意的. 所有代码都在Razor For循环内进行:

NEW EXAMPLE First of all I want to apologize. I've been hiding information, of course totally unintentionally. All the code happens inside a Razor For Loop:

@foreach (var loopVariable in Model.Collection)
{
    if (Model.SomeCondition != null)
    {
        selection = someValue;
    }

    var selectList = new List<SelectListItem>(
      from variable in someKindOfCollection
      select new SelectListItem
    {
        Selected = variable.Property == selection,
        Text = variable.Property,
        Value = variable.Property
    });

    @Html.DropDownListFor(
        g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })

}

因此,selectList的事实是导致该行为的局部变量?抱歉,我没想到是那样.

So, It's the fact of selectList is a local variable causing the behavior?. Sorry, I didn't thought it was that.

推荐答案

我认为您遇到的是我遇到的相同问题.我浏览了源代码以找到解决方案,这似乎对我来说是个错误.以下DropDownListFor应该会有所帮助,其关键是将所选值传递到html帮助器中.希望这会有所帮助.

I think you are having the same problem i did. I looked through the source code to find my solution and it appears this is a bug to me. The following DropDownListFor should help, the key to it is that you pass the selected value into the html helper. Hope this helps.

public static class SelectExtensions {
    public static IHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string selectedValue, string optionLabel, object htmlAttributes = null) {
       return DropDownListHelper(helper, ExpressionHelper.GetExpressionText(expression), selectList, selectedValue, optionLabel, htmlAttributes);
    }

    /// <summary>
    /// This is almost identical to the one in ASP.NET MVC 3 however it removes the default values stuff so that the Selected property of the SelectListItem class actually works
    /// </summary>
   private static IHtmlString DropDownListHelper(HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, string selectedValue, string optionLabel, object htmlAttributes) {
        name = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

        // Convert each ListItem to an option tag
        var listItemBuilder = new StringBuilder();

        // Make optionLabel the first item that gets rendered
        if (optionLabel != null)
            listItemBuilder.AppendLine(ListItemToOption(new SelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }, selectedValue));

        // Add the other options
        foreach (var item in selectList) {
            listItemBuilder.AppendLine(ListItemToOption(item, selectedValue));
        }

        // Now add the select tag
        var tag = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() };
        tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        tag.MergeAttribute("name", name, true);
        tag.GenerateId(name);

        // If there are any errors for a named field, we add the css attribute
        ModelState modelState;

        if (helper.ViewData.ModelState.TryGetValue(name, out modelState)) {
            if (modelState.Errors.Count > 0)
                tag.AddCssClass(HtmlHelper.ValidationInputCssClassName);
        }

        // Add the unobtrusive validation attributes
        tag.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(name));

        return tag.ToHtmlString(TagRenderMode.Normal);
    }

    private static string ListItemToOption(SelectListItem item, string selectedValue) {
        var tag = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) };

        if (item.Value != null)
            tag.Attributes["value"] = item.Value;

        if ((!string.IsNullOrEmpty(selectedValue) && item.Value == selectedValue) || item.Selected)
            tag.Attributes["selected"] = "selected";

        return tag.ToString(TagRenderMode.Normal);
    }
}

这篇关于SelectListItem中的选定属性永远不起作用(DropDownListFor)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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