我正在尝试动态设置HtmlHelper 的disabled属性TextBoxFor
@Html.TextBoxFor(model => model.Street,
new
{
@class = "",
disabled = (Model.StageID==(int)MyEnum.Sth) ? "disabled" : ""
})
Run Code Online (Sandbox Code Playgroud)
但即使有disabled=""它是一样的disabled="disabled".怎么解决这个问题?
Chu*_*ris 20
我在一个月前遇到了同样的问题,最后我使用了这个扩展方法
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;
}
}
Run Code Online (Sandbox Code Playgroud)
之后你可以像这样使用它
@Html.TextBoxFor(
model => model.Street,
new { @class = "" }.DisabledIf(Model.StageID==(int)MyEnum.Sth)
)
Run Code Online (Sandbox Code Playgroud)
使用的data-xxxHTML属性可以通过使用的构造被开采System.Web.Routing.RouteValueDictionary类,因为下划线不会被自动转换为负号.
请改用System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes方法:将解决此问题.
更新的代码(仅扩展方法体)
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return attributes;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5412 次 |
| 最近记录: |