2011-12-08 96 views
4

我想禁用我的表单中的所有字段,当页面加载时,这些字段具有值。 例如,在此设置可选的禁用属性

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

我想写内嵌这样的事情。我不想使用if-else并使我的代码更大。 使用javascript/jquery也不欢迎。

我试图写虚假/真实,但1.它可能不是跨浏览器2.MVC分析它像字符串“真”和“假”。 那我该怎么做呢?

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

回答

5

似乎是一个很好的候选人定制的帮手:

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

可能像这样被使用:

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

助手可以明显地采取更进一步,因此您不需要传递额外的布尔值,但它会自动确定表达式的值是否等于default(TProperty)并且它应用disabled属性。

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

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) 
) 
+0

谢谢,我用了第二种扩展方法,太棒了! –

0

我用Darin的答案。但是,当涉及到data_my_custom_attribute时,它们未呈现为data-my-custom-attribute。所以我改变了Darin的代码来处理这个问题。

public static RouteValueDictionary DisabledIf(
    this object htmlAttributes, 
    bool disabled 
    ) 
{ 
    RouteValueDictionary htmlAttributesDictionary 
     = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 

    if (disabled) 
    { 
     htmlAttributesDictionary["disabled"] = "disabled"; 
    } 
    return new RouteValueDictionary(htmlAttributesDictionary); 
} 
相关问题