设置可选disabled属性 [英] Set optional disabled attribute

查看:764
本文介绍了设置可选disabled属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想停用我的表格所有领域,其中有值​​时,页面加载。
例如,在此

I want to disable all fields in my form, which have values when page is loaded. For example in this

<td>@Html.TextBoxFor(m => m.PracticeName, new { style = "width:100%", disabled = Model.PracticeName == String.Empty ? "Something Here" : "disabled" })</td>

我想编写内联这样的事情。我不希望使用的if-else,让我的code大。
使用Javascript / jQuery的不欢迎了。

I want to write inline something like this. I don't want to use if-else and make my code larger. Using javascript/jquery doesn't welcome too.

我试着写假/真实的,但也许1.It是不是跨浏览器2.Mvc它解析像真与假字符串。
所以,我该怎么办呢?

I tried to write false/true, but 1.It maybe isn't cross-browser 2.Mvc parsed it to string like "True" and "False". So how can I do it?

P.S。我使用ASP.NET MVC 3:)

P.S. I use ASP.NET MVC 3 :)

推荐答案

似乎是一个不错的选择自定义助手:

Seems like a good candidate for a custom helper:

public static class HtmlExtensions
{
    public static IHtmlString TextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> ex,
        object htmlAttributes,
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(ex, attributes);
    }
}

它可以用来这样的:

which could be used like this:

@Html.TextBoxFor(
    m => m.PracticeName, 
    new { style = "width:100%" }, 
    Model.PracticeName != String.Empty
)

助手可以明显地向前推进了一步,这样你就不需要通过额外的布尔值,但它会自动确定前pression的值是否等于默认( TProperty),并将其应用在禁用属性。

另一种可能性是扩展方法是这样的:

Another possibility is an extension method like this:

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;
    }
}

,你将与标准的使用 TextBoxFor 助手:

@Html.TextBoxFor(
    m => m.PracticeName, 
    new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty)
)

这篇关于设置可选disabled属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆