【问题标题】:ASP.NET MVC Custom dropdown from model with custom HtmlHelper带有自定义 HtmlHelper 的模型中的 ASP.NET MVC 自定义下拉菜单
【发布时间】:2011-03-31 15:37:00
【问题描述】:

我只是在 MVC 中使用 HtmlHelpers,非常有用的东西,现在我正在尝试为下拉菜单创建一个 基于传入模型 ( any ) 的值和文本的属性是什么。

所以我有这样的事情:

public static MvcHtmlString DataFilledDropDown<T>(this HtmlHelper h, string name, T selectedValue)
    {
        var myModel = typeof(T);
        var dropDownBox = new Tag("select").With("name", name).And("id", name);

        foreach (T val in Enum.GetValues(myModel))
        {
            var itemText = Resources.ResourceManager.GetString(val.ToString());
            if (String.IsNullOrEmpty(itemText)) itemText = val.ToString();

            var dft = new Tag("option")
                .With("value", "0")
                .AndIf(val.Equals(selectedValue), "selected", "selected")
                .WithText("-- CHOOSE --");
            dropDownBox.Append(dft);

            var option = new Tag("option")
                .With("value", (val).ToString())
                .AndIf(val.Equals(selectedValue), "selected", "selected")
                .WithText(itemText);
            dropDownBox.Append(option);
        }
        return MvcHtmlString.Create(dropDownBox.ToString());

    }

但这只会涵盖我的单个字段,但我的模型可能是这样的:

public class TestModel{
     public int Id {get; set; } // this i want as a value in dropdown
     public string Name {get;set;} // this i want to be the text value in dropdown
     public bool isActive { get; set; } // this i dont need in dropdown but have data in model
 }

所以上面我想创建这样的东西:

Html.DataFilledDropDown<myModel>("TestDropdown","Id","Name","0")

其中输入是下拉列表的名称、值属性的名称、文本属性的名称和默认选择值

我在下面的答案的帮助下完成了这个,这是任何有兴趣的人的代码:

public static MvcHtmlString DataFilledDropDown<T>(
        this HtmlHelper h, string name, IEnumerable<T> items, 
        Func<T,string> valueField, Func<T,string> textField, string selectedValue)
    {
        var dropDownBox = new Tag("select").With("name", name).And("id", name);
        var defaultValue = "0";
        var dft = new Tag("option")
                .With("value", "0")
                .AndIf(defaultValue.Equals(selectedValue), "selected", "selected")
                .WithText("-- CHOOSE --");
        dropDownBox.Append(dft);

        foreach (var item in items)
        {
            var myValue = valueField(item);
            var myName = textField(item);

            var option = new Tag("option")
                .With("value", myValue)
                .AndIf(myValue.Equals(selectedValue), "selected", "selected")
                .WithText(myName);
            dropDownBox.Append(option);

        }

        return MvcHtmlString.Create(dropDownBox.ToString());
    }

并运行代码

<%: Html.DataFilledDropDown("SpexOptionType", Model.Clubs, x => x.clubID.ToString(), x => x.clubName, "0")%>

就是这样

非常感谢

【问题讨论】:

  • 您应该接受答案,如果这足以解决您的问题。
  • 你能贴出'Tag'类的代码吗?它来自图书馆吗?谢谢
  • 我不认为“标签”对象存在——它在 MVC3 中肯定不存在.....

标签: asp.net asp.net-mvc asp.net-mvc-3 c#-4.0 html-helper


【解决方案1】:

我知道这并不能直接回答您的问题,但我建议您不要使用字符串作为您的姓名和 ID。随着时间的推移,它们存在问题并且难以维护。而是使用 Func。

这是我用于选择列表的内容:

public static string SelectList<T>(this HtmlHelper html, T root, IEnumerable<T> items, Func<T, string> itemValueContent,
                            Func<T, string> itemTextContent, Func<T, IEnumerable<T>> childrenProperty, Func<T, string> parentProperty, string selectSize)
    {
        StringBuilder parentSb = new StringBuilder();
        StringBuilder childSb = new StringBuilder();

        parentSb.AppendFormat("<select class='parent' name='parent' size='{0}'>\r\n", selectSize);
        childSb.AppendFormat("<select class='child' id='child' size='{0}'>\r\n", selectSize);

        foreach (T parentItem in items)
        {
            foreach (T item in childrenProperty(parentItem))
            {
                RenderParentOption(parentSb, item, itemValueContent, itemTextContent);

                foreach (T item1 in childrenProperty(item))
                {
                    RenderOptionWithClass(childSb, item1, itemValueContent, itemTextContent, parentProperty);
                }
            }                
        }



        parentSb.AppendLine("</select>");
        childSb.AppendLine("</select>");


        return parentSb.ToString() + childSb.ToString();
    }


    private static void RenderOptionWithClass<T>(StringBuilder sb, T item, Func<T, string> itemValueContent, Func<T, string> itemTextContent, Func<T, string> parentProperty)
    {
        sb.AppendFormat("<option class='sub_{2}' value='{0}'>{1}</option>\r\n", itemValueContent(item), itemTextContent(item), parentProperty(item));
    }

    private static void RenderParentOption<T>(StringBuilder sb, T item, Func<T, string> itemValueContent, Func<T, string> itemTextContent)
    {
        sb.AppendFormat("<option value='{0}'>{1}</option>\r\n", itemValueContent(item), itemTextContent(item) + " ->");
    }

它是这样使用的:

<%=Html.SelectList<HierarchyNode<CategoryModel>>(Model.CategoryList.First(), Model.CategoryList,
       x => x.Entity.RowId.ToString(),
       x => x.Entity.Name.ToString(),
       x => x.ChildNodes,
       x => x.Entity.ParentCategoryId.ToString(), "10")%>

【讨论】:

  • 谢谢,我不确定您似乎在哪里创建 2 个下拉列表,这一切似乎有点令人困惑,但我已经记录了有关 Func 的注释,并使用它来修改我的版本以现在可以实际使用所以谢谢你的提示。如果您想查看,我已经修改了我的帖子以显示解决方案。 ta
  • 抱歉,代码正在创建一个带有嵌套列表的树视图。如果您需要一些帮助以使其正常工作,请再次发布。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 2018-07-03
相关资源
最近更新 更多