【问题标题】:Using Extension Methods in ASP.NET MVC在 ASP.NET MVC 中使用扩展方法
【发布时间】:2015-02-19 15:59:56
【问题描述】:

我是 ASP.NET MVC 的新手。我继承了我正在尝试使用的代码库。我需要添加一些基本的 HTML 属性。目前,在我的 .cshtml 文件中,有这样一个块:

@Html.DropDown(model => model.SomeValue, Model.SomeList)

这引用了Extensions.cs 中的一个函数。该函数如下所示:

public static MvcHtmlString DropDown<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IEnumerable<string> items, string classes = "form-control")
{
  var attributes = new Dictionary<string, object>();
  attributes.Add("class", classes);

  return System.Web.Mvc.Html.SelectExtensions.DropDownListFor(html, expression, itemList.Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }), null, attributes);
}

我现在有一个案例,我需要在某些情况下禁用下拉菜单。我需要评估Model.IsUnknown 的值(这是一个布尔值)以确定是否应启用下拉列表。

我的问题是,如果需要,如何禁用下拉列表?此时,我不知道是否需要更新我的 .cshtml 或扩展方法。

感谢您提供的任何指导。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor


    【解决方案1】:

    在您的扩展方法中添加一个可选参数以禁用名为enabled,默认为true,并从视图传递bool 参数以禁用或启用它:

    public static MvcHtmlString DropDown<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IEnumerable<string> items, string classes = "form-control",bool enabled=true)
    {
      var attributes = new Dictionary<string, object>();
      attributes.Add("class", classes);
      if(!enabled)
         attributes.Add("disabled","disabled");
    
      return System.Web.Mvc.Html.SelectExtensions.DropDownListFor(html, expression, itemList.Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }), null, attributes);
    }
    

    现在在视图中:

    @Html.DropDown(model => model.SomeValue, Model.SomeList,enabled:false)
    

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多