【问题标题】:Html.DropDownListFor() with custom parameter带有自定义参数的 Html.DropDownListFor()
【发布时间】:2011-12-14 13:25:17
【问题描述】:

我想在 HTML 帮助器中添加扩展方法来生成这样的选择和选项

<select id="Country" name="Country">
<option data-domain="AN" value="1">Andorra</option>
<option data-domain="UI" value="2">United Arab Emirates</option>
<option data-domain="AF" value="3">Afghanistan</option>

这些选项有一个数据域属性,我可以这样使用它

@Html.DropDownListFor(m => m.Country, Model.CountryList)

Model.CountryList 是 Country 变量的数组

class Country
{
    public String Text { get; set; }
    public String Value { get; set; }
    public String Domain { get; set; }
}

谁能给个解决办法

【问题讨论】:

    标签: html asp.net-mvc asp.net-mvc-3 select


    【解决方案1】:

    您可以在自定义帮助方法的帮助下构建您的CustomDropdownListFor,如下所示:

    自定义辅助方法:

    public static class CustomHelpers
    {    
        public class CustomSelectItem : SelectListItem
        {           
            public string Class { get; set; } 
            public string Disabled { get; set; }
            public string SelectedValue { get; set; }
        }
    
        public static MvcHtmlString CustomDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<CustomSelectItem> list, string selectedValue, string optionLabel, object htmlAttributes = null)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
            string name = ExpressionHelper.GetExpressionText((LambdaExpression)expression);
            return CustomDropdownList(htmlHelper, metadata, name, optionLabel, list, selectedValue, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }
    
        private static MvcHtmlString CustomDropdownList(this HtmlHelper htmlHelper, ModelMetadata metadata, string name, string optionLabel, IEnumerable<CustomSelectItem> list, string selectedValue, IDictionary<string, object> htmlAttributes)
        {
            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            if (String.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException("name");
            }
    
            TagBuilder dropdown = new TagBuilder("select");
            dropdown.Attributes.Add("name", fullName);
            dropdown.MergeAttribute("data-val", "true");
            dropdown.MergeAttribute("data-val-required", "Mandatory field.");
            dropdown.MergeAttribute("data-val-number", "The field must be a number.");          
            dropdown.MergeAttributes(htmlAttributes); //dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            dropdown.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)); 
    
            StringBuilder options = new StringBuilder();
    
            // Make optionLabel the first item that gets rendered.
            if (optionLabel != null)
                options.Append("<option value='" + String.Empty + "'>" + optionLabel + "</option>");
    
            foreach (var item in list)
            {
                if (item.SelectedValue == "selected" && item.Disabled == "disabled")
                    options.Append("<option value='" + item.Value + "' class='" + item.Class + "' selected='" + item.SelectedValue + "' disabled='" + item.Disabled + "'>" + item.Text + "</option>");
                else if (item.SelectedValue != "selected" && item.Disabled == "disabled")
                    options.Append("<option value='" + item.Value + "' class='" + item.Class + "' disabled='" + item.Disabled + "'>" + item.Text + "</option>");
                else if (item.SelectedValue == "selected" && item.Disabled != "disabled")
                    options.Append("<option value='" + item.Value + "' class='" + item.Class + "' selected='" + item.SelectedValue + "'>" + item.Text + "</option>");
                else
                    options.Append("<option value='" + item.Value + "' class='" + item.Class + "'>" + item.Text + "</option>");
            }
            dropdown.InnerHtml = options.ToString();
            return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal));
        }
    }
    


    查看(剃刀):

    @Html.CustomDropdownListFor(m => m.PersonId, ViewBag.PersonData as List<CustomHelpers.CustomSelectItem>, null, "---- Select ----", 
        new { name = "personId", id = "personId"})                   
    @Html.ValidationMessageFor(m => m.PersonId, null , new { @class = "ValidationErrors" })
    

    希望这会有所帮助...

    【讨论】:

    【解决方案2】:

    标准的DropDownList/DropDownListFor 助手不支持这个。如果您需要此类功能,则必须从头开始编写自定义 HTML 帮助程序。您可以结帐this example。还有another one

    【讨论】:

      【解决方案3】:

      方法:

       public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListCodeItem> selectList)
              {
                  var select = new TagBuilder("select");
      
                  var options = "";
                  TagBuilder option;
      
                  foreach (var item in selectList)
                  {
                      option = new TagBuilder("option");
                      option.MergeAttribute("value", item.Value.ToString());
                      option.MergeAttribute("data-domain", item.Code.ToString());
                      option.SetInnerText(item.Text);
                      options += option.ToString(TagRenderMode.Normal) + "\n";
                  }
      
                  select.MergeAttribute("data-val", "true");
                  select.MergeAttribute("data-val-required", "The field is required.");
                  select.MergeAttribute("id", name);
                  select.MergeAttribute("name", name);
      
                  select.InnerHtml = options;
      
                  return new MvcHtmlString(select.ToString(TagRenderMode.Normal));
              }
      

      呼叫:

      @Html.DropDownList("name" Model.OrganizationTypeList)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-21
        • 1970-01-01
        • 2013-06-17
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多