使用ASP.NET MVC扩展方法

编程入门 行业动态 更新时间:2024-10-16 00:17:23
本文介绍了使用ASP.NET MVC扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我新的ASP.NET MVC。我继承了我想一起工作一个code基地。我有一个需要添加一些基本的HTML属性。目前,在我的.cshtml文件,有一个块是这样的:

I am new to ASP.NET MVC. I have inherited a code base that I am trying to work with. I have a need to add some basic HTML attributes. Currently, in my .cshtml file, there is a block like this:

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

这引用了 Extensions.cs 的功能。此功能如下所示:

This references a function in Extensions.cs. This function looks like the following:

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 (这是一个布尔值)的值,以确定在下拉列表中是否不应该被启用。

I now have a case where I need to disable the drop down in some scenarios. I need to evaluate the value of Model.IsUnknown (which is a bool) to determine whether or not the drop down list should be enabled or not.

我的问题是,我该如何禁用一个下拉列表,如果我需要?在这一点上,我不知道我是否需要更新我的.cshtml或扩展方法。

My question is, how do I disable a drop down list if I need to? At this point, I do not know if I need to update my .cshtml or the extension method.

感谢您为您提供任何指导。

Thank you for any guidance you can provide.

推荐答案

在您的扩展方法添加一个可选的参数禁用名为启用和bydefaut这将是真正并从该视图通布尔参数来禁用或启用它:

Add an optional parameter in your extension method for disabling named enabledand bydefaut it will be true and from view pass bool parameter to disable or enable it:

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)

更多推荐

使用ASP.NET MVC扩展方法

本文发布于:2023-10-11 10:15:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1481411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   ASP   NET   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!