2012-02-27 51 views
0

我用一个文本框执行以下操作:为TextBoxFor附加参数()在ASP.net MVC3

<input style="width:50px;" type="text" id="blah" value="@model.value1" @if(model.id!=1){ <text>disabled</text>}/>

这基本上示出了在特定情况下禁用的文本框。 我决定用更“mvc友好”的方式取代它。

@Html.TextBoxFor(m => model.value1, new { id = "blah" })

,但不知道如何禁用属性添加(动态),我可以得到它通过将disabled=true值到new{}做静态easilly。

我曾尝试使用此: @if (<condition>) { var disable = true; } @Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = disable })

但是,这也没有工作。我在这里采取正确的方法吗?

回答

3
@{ 
    var attributes = new Dictionary<string, object> 
    { 
     { "id", "blah" } 
    }; 
    if (<condition>) 
    { 
     attributes["disabled"] = "disabled"; 
    } 
} 
@Html.TextBoxFor(m => model.value1, attributes) 

显然,这是丑陋的地狱,你应该从来没有思考污染你的观点那样的。我只想写一个自定义的可重复使用的HTML帮助:

public static class HtmlExtensions 
{ 
    public static IHtmlString MyTextBoxFor<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.MyTextBoxFor(m => model.value1, new { id = "blah" }, <condition>) 
+0

谢谢,仍然习惯于自定义HtmlHelpers。真正有用的信息! – JustAnotherDeveloper 2012-02-27 12:17:15

1

您有上述禁用范围问题不if语句的范围之外存在,

我的建议是这样的:

@Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) }) 

编辑:

您可以使用

@Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) ? "disabled" : "" }) 

如果要插入禁用的词而不是bo OL,从内存,这是有点浏览器特定设置一些很高兴能与“真”人与“禁用”

+0

这证实了罚款,但我用的是“禁用”它认为作为即时通讯自动禁用该框。 – JustAnotherDeveloper 2012-02-27 11:42:25

+0

查看我的编辑,你可以使用一个三元运算符联机,根据if语句给出不同的值。 – 2012-02-28 02:57:39

+0

禁用关键字会自动禁用输入 – hjgraca 2014-12-03 15:14:48