@ Html.DropDownList()占位符为禁用和选中

时间:2017-10-20 09:20:30

标签: c# asp.net-mvc asp.net-mvc-5

如果我使用带有静态值的@Html.DropDownList(),则可以将占位符创建为第一个选项,并且可以对此选项应用“已禁用”和“已选择”属性,如此

@Html.DropDownList("month", new List<SelectListItem>
{
    new SelectListItem{ Text="Select Month", Value = "0" , Disabled = true, Selected = true},
    new SelectListItem{ Text="January", Value = "1" },
    new SelectListItem{ Text="February", Value = "2" },
    new SelectListItem{ Text="March", Value = "3" },
    new SelectListItem{ Text="April", Value = "4" },
    new SelectListItem{ Text="May", Value = "5" },
    new SelectListItem{ Text="June", Value = "6" },
    new SelectListItem{ Text="July", Value = "7" },
    new SelectListItem{ Text="August", Value = "8" },
    new SelectListItem{ Text="September", Value = "9" },
    new SelectListItem{ Text="October", Value = "10" },
    new SelectListItem{ Text="November", Value = "11" },
    new SelectListItem{ Text="December", Value = "12" },
}, new {@class = "form-control"})

但是,如果我创建一个类似于数字范围的下拉列表,并像这样制作一个Place持有者:

@Html.DropDownList("year", 
      Enumerable.Range(1900, 200)
          .Select(i => new SelectListItem { Text = i.ToString(), Value = i.ToString() }), 
      "Please Select Year", new { @class = "form-control" })

是否可以将此Please Select Year禁用并选中?

This is the output of first dropdownlist where first option is Disabled

I want this please Select Year as Disabled

3 个答案:

答案 0 :(得分:6)

请注意,您在$search = autocomplete('products',$search_term); <input value="<?=$search_term; ?>" onkeydown="$search" type='text' name='product'> 下拉列表中使用的重载使您无法控制默认项​​目外观。

然而,您可以使用相同的方法恢复您使用的相同方法,只需要一点点代码:

year

答案 1 :(得分:0)

DropDownListFor允许指定一个占位符,但是未选择生成的option,也未禁用。

我想出了这个

public static MvcHtmlString CustomDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, IEnumerable<SelectListItem> items, string placeHolder, object htmlAttributes)
{
    var r = htmlHelper.DropDownListFor(expression, items, placeHolder, htmlAttributes).ToString();
    var loc = r.IndexOf(placeHolder);
    r = r.Insert(loc - 1, $" selected disabled");
    return new MvcHtmlString(r);
}

当然,如果您想要更可靠的东西,也许可以使用HtmlAgilityPack进行解析。

答案 2 :(得分:0)

基于另一个答案,我为HtmlHelper编写了一些扩展,使扩展易于实现。

要在代码中实现,只需使用如下:

@Html.DropDownListWithDisabledFirstItemFor(model => model.MyProperty, new SelectList(source, "ID_Property", "Display_Property"), "Select an item")

更改:

  • model.MyProperty到模型\ viewmodel中的属性名称。
  • source到您的下拉列表的源集合。
  • ID_Propertysource中类型的ID属性的名称。
  • Display_Propertysource中类型的显示属性的名称。
  • Select an item到要显示在下拉列表的禁用项目中的文本。

DropDownListWithDisabledFirstItemFor方法的重载也允许指定HTML属性。如果需要其他版本的DropDownListFor,扩展可能会进一步过载。

为什么选择这个而不是接受的答案?

我不喜欢可以为下拉列表指定选项标签但启用了该选项的想法。内置功能应该能够自动禁用它,而无需手动添加SelectListItem

此外,我真的不喜欢在客户端上使用JavaScript来禁用select中的第一个选项的想法(这是另一篇文章中的建议)。对我来说,这简直像是一桩骇客。

此实现允许继续使用选项标签,而无需对SelectList进行任何操作。

扩展代码

扩展代码位于下面的HtmlHelperExtensions类中:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

/// <summary>
/// A class that defines extension methods for a HTML helper.
/// </summary>
public static class HtmlHelperExtensions
{
    #region Methods
    #region _Private_
    private static MvcHtmlString DisableDropDownItem(MvcHtmlString source, string sourceItemName, string sourceItemValue = "", string targetItemValue = "")
    {
        string htmlString;
        MvcHtmlString returnValue;
        string sourceString;

        sourceString = $"<option value=\"{sourceItemValue}\">{sourceItemName}</option>";

        htmlString = source.ToHtmlString();
        if (htmlString.Contains(sourceString))
        {
            string replaceString;

            replaceString = $"<option value=\"{targetItemValue}\" disabled=\"disabled\" selected=\"selected\">{sourceItemName}</option>";
            htmlString = htmlString.Replace(sourceString, replaceString);
        }
        returnValue = new MvcHtmlString(htmlString);

        return returnValue;
    }

    #endregion
    #region _Public_
    /// <summary>
    /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items, and option label, with the opton label disabled.
    /// </summary>
    /// <typeparam name="TModel">The type of the model.</typeparam>
    /// <typeparam name="TProperty">The type of the value.</typeparam>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="expression">An expression that identifies the object that contains the properties to display.</param>
    /// <param name="selectList">An IEnumerable of SelectListItem objects that are used to populate the drop-down list.</param>
    /// <param name="optionLabel">A string containing the text for a default empty item. This parameter can be null.</param>
    /// <param name="optionLabelValue">A string containing the value that should be assigned to the option label.</param>
    /// <returns>An HTML select element for each property in the object that is represented by the expression.</returns>
    public static MvcHtmlString DropDownListWithDisabledFirstItemFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, int optionLabelValue = 0)
    {
        return DisableDropDownItem(htmlHelper.DropDownListFor(expression, selectList, optionLabel), optionLabel, string.Empty, optionLabelValue.ToString());
    }
    /// <summary>
    /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items, option label, and HTML attributes, with the opton label disabled.
    /// </summary>
    /// <typeparam name="TModel">The type of the model.</typeparam>
    /// <typeparam name="TProperty">The type of the value.</typeparam>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="expression">An expression that identifies the object that contains the properties to display.</param>
    /// <param name="selectList">An IEnumerable of SelectListItem objects that are used to populate the drop-down list.</param>
    /// <param name="optionLabel">A string containing the text for a default empty item. This parameter can be null.</param>
    /// <param name="htmlAttributes">An IDictionary of key string and value object that contains the HTML attributes to set for the element.</param>
    /// <param name="optionLabelValue">A string containing the value that should be assigned to the option label.</param>
    /// <returns>An HTML select element for each property in the object that is represented by the expression.</returns>
    public static MvcHtmlString DropDownListWithDisabledFirstItemFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes, int optionLabelValue = 0)
    {
        return DisableDropDownItem(htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes), optionLabel, string.Empty, optionLabelValue.ToString());
    }
    /// <summary>
    /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items, option label, and HTML attributes, with the opton label disabled.
    /// </summary>
    /// <typeparam name="TModel">The type of the model.</typeparam>
    /// <typeparam name="TProperty">The type of the value.</typeparam>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="expression">An expression that identifies the object that contains the properties to display.</param>
    /// <param name="selectList">An IEnumerable of SelectListItem objects that are used to populate the drop-down list.</param>
    /// <param name="optionLabel">A string containing the text for a default empty item. This parameter can be null.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param>
    /// <param name="optionLabelValue">A string containing the value that should be assigned to the option label.</param>
    /// <returns>An HTML select element for each property in the object that is represented by the expression.</returns>
    public static MvcHtmlString DropDownListWithDisabledFirstItemFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes, string optionLabelValue = "0")
    {
        return DisableDropDownItem(htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes), optionLabel, string.Empty, optionLabelValue);
    }

    #endregion
    #endregion
}