解决asp.net mvc下拉列表选定值覆盖器问题

发布于 2024-10-15 07:13:15 字数 4711 浏览 2 评论 0原文

我编写了一个辅助方法,将我的 asp.net MVC 应用程序中的模型中的枚举显示为视图中的下拉列表。

这是我的代码:

public static List<SelectListItem> CreateSelectItemList<TEnum>(object enumObj,
                                                            string defaultItemKey,
                                                            bool sortAlphabetically,
                                                            object firstValueOverride)
    where TEnum : struct
    {
        var values = (from v in (TEnum[])Enum.GetValues(typeof(TEnum))
                      select new
                      {
                          Id = Convert.ToInt32(v),
                          Name = ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace,
                                                                  typeof(TEnum).Name, v.ToString())
                      });


        return values.ToSelectList(e => e.Name,
                                               e => e.Id.ToString(),
                                               !string.IsNullOrEmpty(defaultItemKey) ? ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace, defaultItemKey) : string.Empty,
                                               enumObj,
                                               sortAlphabetically,
                                               firstValueOverride);

    }

这实际上生成了选择项列表:

public static List<SelectListItem> ToSelectList<T>(
    this IEnumerable<T> enumerable,
    Func<T, string> text,
    Func<T, string> value,
    string defaultOption,
    object selectedVal,
    bool sortAlphabetically,
    object FirstValueOverride)
{

    int iSelectedVal = -1;

    if(selectedVal!=null)
    {
        try
        {
            iSelectedVal = Convert.ToInt32(selectedVal);
        }
        catch
        {
        }
    }

    var items = enumerable.Select(f => new SelectListItem()
    {
        Text = text(f),
        Value = value(f),
        Selected = (iSelectedVal > -1)? (iSelectedVal.ToString().Equals(value(f))) : false
    });

    #region Sortare alfabetica
    if (sortAlphabetically)
        items = items.OrderBy(t => t.Text);
    #endregion Sortare alfabetica

    var itemsList = items.ToList();

    Func<SelectListItem, bool> funct = null;
    string sValue = string.Empty;
    SelectListItem firstItem = null;
    SelectListItem overridenItem = null;
    int overridenIndex = 0;

    if (FirstValueOverride != null)
    {
        sValue = FirstValueOverride.ToString();

        funct = (t => t.Value == sValue);
        overridenItem = itemsList.SingleOrDefault(funct);
        overridenIndex = itemsList.IndexOf(overridenItem);

        if (overridenItem != null)
        {
            firstItem = itemsList.ElementAt(0);
            itemsList[0] = overridenItem;
            itemsList[overridenIndex] = firstItem;
        }
    }

    if(!string.IsNullOrEmpty(defaultOption))
        itemsList.Insert(0, new SelectListItem()
        {
            Text = defaultOption,
            Value = "-1"
        });

    return itemsList;
}

这是我调用的方法:

        public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, 
                                                        object enumObj,
                                                        string name,
                                                        string defaultItemKey,
                                                        bool sortAlphabetically,
                                                        object firstValueOverride,
                                                        object htmlAttributes)
    where TEnum : struct
    {
        return htmlHelper.DropDownList(name,
                                        CreateSelectItemList<TEnum>(enumObj,
                                                                defaultItemKey,
                                                                sortAlphabetically,
                                                                firstValueOverride), 
                                         htmlAttributes);
    }

现在我遇到了所描述的问题 此处
当我调用此帮助器方法并且输入的名称与属性名称相同时,不会选择所选值。
那里描述的替代解决方案对我不起作用。唯一有效的解决方案是更改名称,而不是使用 FormCollection 进行模型绑定。 我不喜欢这种解决方法,因为我无法再使用 ViewModel 模式进行验证,而且我必须为每个枚举编写一些额外的代码。
我尝试编写一个自定义模型绑定器来以某种方式补偿这一点,但是当我开始操作时,我可以覆盖的方法都不会被调用。

有没有办法在不使用 FormCollection 的情况下做到这一点? 当 ASP.NET MVC 尝试将值放入我的输入字段并使其选择正确的值时,我是否可以以某种方式拦截它?

先感谢您。

I wrote a helper method to display enums from my model in my asp.net MVC application as drop down lists in my views.

Here is my code for that:

public static List<SelectListItem> CreateSelectItemList<TEnum>(object enumObj,
                                                            string defaultItemKey,
                                                            bool sortAlphabetically,
                                                            object firstValueOverride)
    where TEnum : struct
    {
        var values = (from v in (TEnum[])Enum.GetValues(typeof(TEnum))
                      select new
                      {
                          Id = Convert.ToInt32(v),
                          Name = ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace,
                                                                  typeof(TEnum).Name, v.ToString())
                      });


        return values.ToSelectList(e => e.Name,
                                               e => e.Id.ToString(),
                                               !string.IsNullOrEmpty(defaultItemKey) ? ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace, defaultItemKey) : string.Empty,
                                               enumObj,
                                               sortAlphabetically,
                                               firstValueOverride);

    }

This actually generates the select item list:

public static List<SelectListItem> ToSelectList<T>(
    this IEnumerable<T> enumerable,
    Func<T, string> text,
    Func<T, string> value,
    string defaultOption,
    object selectedVal,
    bool sortAlphabetically,
    object FirstValueOverride)
{

    int iSelectedVal = -1;

    if(selectedVal!=null)
    {
        try
        {
            iSelectedVal = Convert.ToInt32(selectedVal);
        }
        catch
        {
        }
    }

    var items = enumerable.Select(f => new SelectListItem()
    {
        Text = text(f),
        Value = value(f),
        Selected = (iSelectedVal > -1)? (iSelectedVal.ToString().Equals(value(f))) : false
    });

    #region Sortare alfabetica
    if (sortAlphabetically)
        items = items.OrderBy(t => t.Text);
    #endregion Sortare alfabetica

    var itemsList = items.ToList();

    Func<SelectListItem, bool> funct = null;
    string sValue = string.Empty;
    SelectListItem firstItem = null;
    SelectListItem overridenItem = null;
    int overridenIndex = 0;

    if (FirstValueOverride != null)
    {
        sValue = FirstValueOverride.ToString();

        funct = (t => t.Value == sValue);
        overridenItem = itemsList.SingleOrDefault(funct);
        overridenIndex = itemsList.IndexOf(overridenItem);

        if (overridenItem != null)
        {
            firstItem = itemsList.ElementAt(0);
            itemsList[0] = overridenItem;
            itemsList[overridenIndex] = firstItem;
        }
    }

    if(!string.IsNullOrEmpty(defaultOption))
        itemsList.Insert(0, new SelectListItem()
        {
            Text = defaultOption,
            Value = "-1"
        });

    return itemsList;
}

These is the method I call:

        public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, 
                                                        object enumObj,
                                                        string name,
                                                        string defaultItemKey,
                                                        bool sortAlphabetically,
                                                        object firstValueOverride,
                                                        object htmlAttributes)
    where TEnum : struct
    {
        return htmlHelper.DropDownList(name,
                                        CreateSelectItemList<TEnum>(enumObj,
                                                                defaultItemKey,
                                                                sortAlphabetically,
                                                                firstValueOverride), 
                                         htmlAttributes);
    }

Now I am having the problem described here
When I call this helper method and the input's name is the same as the property's name the selected value doesn't get selected.
The alternate solution described there doesn't work for me. The only solution that works is changing the name and not using the model binding using FormCollection instead.
I don't like this workaround because I can't use validation any more using the ViewModel pattern and I have to write some extra code for every enum.
I tried writing a custom model binder to compensate for this somehow but none of the methods I can override there gets called when I start the action.

Is there any way to do this without using FormCollection?
Can I somehow intercept ASP.NET MVC when it tries to put the value into my input field and make it select the right value?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百善笑为先 2024-10-22 07:13:15

我现在有解决方案
这是 EnumDropDownList 函数的代码,问题中列出了其他函数:

public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper,
                                                   object enumObj,
                                                   string name,
                                                   string defaultItemKey,
                                                   bool sortAlphabetically,
                                                   object firstValueOverride,
                                                   object htmlAttributes)
{

    StringBuilder sbRezultat = new StringBuilder();

    int selectedIndex = 0;

    var selectItemList = new List<SelectListItem>();


    if (enumObj != null)
    {
        selectItemList = CreateSelectItemList(enumObj, defaultItemKey, true, null);

        var selectedItem = selectItemList.SingleOrDefault(item => item.Selected);
        if (selectedItem != null)
        {
            selectedIndex = selectItemList.IndexOf(selectedItem);

        }
    }

    var dict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);


    TagBuilder tagBuilder = new TagBuilder("select");

    tagBuilder.MergeAttribute("name", name,true);

    bool bReadOnly = false;

    //special case for readonly
    if(dict.ContainsKey("readonly"))
    {
        //remove this tag it won't work the way mvc renders it anyway
        dict.Remove("readonly");
        bReadOnly = true;
    }

    //in case the style element is completed if the drop down is not readonly
    tagBuilder.MergeAttributes(dict, true);

    if (bReadOnly)
    {
        //add a small javascript to make it readonly and add the lightgrey style
        tagBuilder.MergeAttribute("onchange", "this.selectedIndex=" + selectedIndex + ";",true);
        tagBuilder.MergeAttribute("style", "background: lightgrey", true);
    }

    sbRezultat.Append(tagBuilder.ToString(TagRenderMode.StartTag));


    foreach (var option in selectItemList)
    {
        sbRezultat.Append(" <option value='");
        sbRezultat.Append(option.Value);
        sbRezultat.Append("' ");
        if (option.Selected)
            sbRezultat.Append("selected");
        sbRezultat.Append(" >");
        sbRezultat.Append(option.Text);


        sbRezultat.Append("</option>");
    }
    sbRezultat.Append("</select>");
    return new MvcHtmlString(sbRezultat.ToString());
}

我还编写了一个 For (EnumDropDownFor): 类型的通用函数:

public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
                                string defaultItemKey,
                                bool sortAlphabetically,
                                object firstValueOverride,
                                object htmlAttributes)
    where TProperty : struct
{
    string inputName = GetInputName(expression);

    object selectedVal = null;
    try
    {
        selectedVal = htmlHelper.ViewData.Model == null
            ? default(TProperty)
            : expression.Compile()(htmlHelper.ViewData.Model);
    }
    catch//in caz ca e ceva null sau ceva de genu'
    {
    }

    return EnumDropDownList(htmlHelper,
                            selectedVal,
                            inputName,
                            defaultItemKey,
                            sortAlphabetically,
                            firstValueOverride,
                            htmlAttributes);
}

和一些辅助方法:

public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
    if (expression.Body.NodeType == ExpressionType.Call)
    {
        MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
        string name = GetInputName(methodCallExpression);
        return name.Substring(expression.Parameters[0].Name.Length + 1);

    }
    return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
}

private static string GetInputName(MethodCallExpression expression)
{
    MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
    if (methodCallExpression != null)
    {
        return GetInputName(methodCallExpression);
    }
    return expression.Object.ToString();
}

I have a sollution now
Here is the code for the EnumDropDownList function the other functions are listed in the question:

public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper,
                                                   object enumObj,
                                                   string name,
                                                   string defaultItemKey,
                                                   bool sortAlphabetically,
                                                   object firstValueOverride,
                                                   object htmlAttributes)
{

    StringBuilder sbRezultat = new StringBuilder();

    int selectedIndex = 0;

    var selectItemList = new List<SelectListItem>();


    if (enumObj != null)
    {
        selectItemList = CreateSelectItemList(enumObj, defaultItemKey, true, null);

        var selectedItem = selectItemList.SingleOrDefault(item => item.Selected);
        if (selectedItem != null)
        {
            selectedIndex = selectItemList.IndexOf(selectedItem);

        }
    }

    var dict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);


    TagBuilder tagBuilder = new TagBuilder("select");

    tagBuilder.MergeAttribute("name", name,true);

    bool bReadOnly = false;

    //special case for readonly
    if(dict.ContainsKey("readonly"))
    {
        //remove this tag it won't work the way mvc renders it anyway
        dict.Remove("readonly");
        bReadOnly = true;
    }

    //in case the style element is completed if the drop down is not readonly
    tagBuilder.MergeAttributes(dict, true);

    if (bReadOnly)
    {
        //add a small javascript to make it readonly and add the lightgrey style
        tagBuilder.MergeAttribute("onchange", "this.selectedIndex=" + selectedIndex + ";",true);
        tagBuilder.MergeAttribute("style", "background: lightgrey", true);
    }

    sbRezultat.Append(tagBuilder.ToString(TagRenderMode.StartTag));


    foreach (var option in selectItemList)
    {
        sbRezultat.Append(" <option value='");
        sbRezultat.Append(option.Value);
        sbRezultat.Append("' ");
        if (option.Selected)
            sbRezultat.Append("selected");
        sbRezultat.Append(" >");
        sbRezultat.Append(option.Text);


        sbRezultat.Append("</option>");
    }
    sbRezultat.Append("</select>");
    return new MvcHtmlString(sbRezultat.ToString());
}

I also wrote a generic function of type For (EnumDropDownFor):

public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
                                string defaultItemKey,
                                bool sortAlphabetically,
                                object firstValueOverride,
                                object htmlAttributes)
    where TProperty : struct
{
    string inputName = GetInputName(expression);

    object selectedVal = null;
    try
    {
        selectedVal = htmlHelper.ViewData.Model == null
            ? default(TProperty)
            : expression.Compile()(htmlHelper.ViewData.Model);
    }
    catch//in caz ca e ceva null sau ceva de genu'
    {
    }

    return EnumDropDownList(htmlHelper,
                            selectedVal,
                            inputName,
                            defaultItemKey,
                            sortAlphabetically,
                            firstValueOverride,
                            htmlAttributes);
}

and some helper methods:

public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
    if (expression.Body.NodeType == ExpressionType.Call)
    {
        MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
        string name = GetInputName(methodCallExpression);
        return name.Substring(expression.Parameters[0].Name.Length + 1);

    }
    return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
}

private static string GetInputName(MethodCallExpression expression)
{
    MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
    if (methodCallExpression != null)
    {
        return GetInputName(methodCallExpression);
    }
    return expression.Object.ToString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文