html.textboxfor属性,根据Html.TextBoxFor的条件设置禁用属性

kooldave98..

10

这已经晚了,但可能对某些人有所帮助.

我已经扩展了@ DarinDimitrov的答案,允许传递第二个对象,它接受任意数量的布尔html属性等disabled="disabled" checked="checked", selected="selected".

仅当属性值为true时才会呈现属性,其他任何内容和属性都不会呈现.

自定义可重用的HtmlHelper:

public static class HtmlExtensions

{

public static IHtmlString MyTextBoxFor(this HtmlHelper htmlHelper,

Expression> expression,

object htmlAttributes,

object booleanHtmlAttributes)

{

var attributes = new RouteValueDictionary(htmlAttributes);

//Reflect over the properties of the newly added booleanHtmlAttributes object

foreach (var prop in booleanHtmlAttributes.GetType().GetProperties())

{

//Find only the properties that are true and inject into the main attributes.

//and discard the rest.

if (ValueIsTrue(prop.GetValue(booleanHtmlAttributes, null)))

{

attributes[prop.Name] = prop.Name;

}

}

return htmlHelper.TextBoxFor(expression, attributes);

}

private static bool ValueIsTrue(object obj)

{

bool res = false;

try

{

res = Convert.ToBoolean(obj);

}

catch (FormatException)

{

res = false;

}

catch(InvalidCastException)

{

res = false;

}

return res;

}

}

您可以这样使用:

@Html.MyTextBoxFor(m => Model.Employee.Name

, new { @class = "x-large" , placeholder = "Type something…" }

, new { disabled = true})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值