动态设置禁用HTML属性为TextBoxFor的HtmlHelper [英] Dynamically set the disabled html attribute for TextBoxFor HtmlHelper
问题描述
我想动态设置为禁用
属性 TextBoxFor
的HtmlHelper
I'm trying to dynamically set the disabled
attribute for the TextBoxFor
HtmlHelper
@Html.TextBoxFor(model => model.Street,
new
{
@class = "",
disabled = (Model.StageID==(int)MyEnum.Sth) ? "disabled" : ""
})
但即使有禁用=
这是一样的禁用=禁用
。如何解决这个?
but even if there is disabled=""
it is the same as disabled="disabled"
. How to get around of this ?
推荐答案
我有同样的问题大约一个月前,我完成了通过使用它这个扩展方法
I have the same problem about month ago and I finished by using this extension method for it
public static class AttributesExtensions
{
public static RouteValueDictionary DisabledIf(
this object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return attributes;
}
}
在这之后,你可以使用它像这样
And after that you can use it like this
@Html.TextBoxFor(
model => model.Street,
new { @class = "" }.DisabledIf(Model.StageID==(int)MyEnum.Sth)
)
修改(后保罗的<一个href=\"http://stackoverflow.com/questions/10207534/dynamically-set-the-disabled-html-attribute-for-textboxfor-htmlhelper/10207597#comment35073920_10207597\">comment):
使用数据-XXX的
HTML属性可以使用的<一个构造函数被开采href=\"https://msdn.microsoft.com/en-us/library/system.web.routing.routevaluedictionary.aspx\">System.Web.Routing.RouteValueDictionary类,因为下划线将不会被自动转换为减号。
The using of data-xxx
html attributes may be mined by using the constructor of the System.Web.Routing.RouteValueDictionary class, since underscores will not be automatically converted to minus sign.
使用方法<一个href=\"https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes.aspx\">System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes代替:将解决这个问题。
Use the method System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes instead: will solve this issue.
修订code (扩展方法仅机身)
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return attributes;
这篇关于动态设置禁用HTML属性为TextBoxFor的HtmlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!