在ASP.NET MVC中使用扩展方法

xam*_*per 0 c# asp.net-mvc razor asp.net-mvc-3 asp.net-mvc-4

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

@Html.DropDown(model => model.SomeValue, Model.SomeList)
Run Code Online (Sandbox Code Playgroud)

这引用了一个函数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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

感谢您提供的任何指导.

Ehs*_*jad 6

在扩展方法中添加一个可选参数,用于禁用named enabled和bydefaut,它将true来自view pass 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);
}
Run Code Online (Sandbox Code Playgroud)

现在在视图中:

@Html.DropDown(model => model.SomeValue, Model.SomeList,enabled:false)
Run Code Online (Sandbox Code Playgroud)