ASP.NET MVC - 使用Model中的布尔值禁用Html Helper控件

时间:2009-08-19 23:39:52

标签: asp.net html asp.net-mvc

我正在使用Html帮助器向页面输出文本框。我想根据模型中的布尔值是真还是假来动态添加disabled属性。

我的模型有一个返回布尔值的方法:

<% =Model.IsMyTextboxEnabled() %>

我目前正在渲染文本框,如下所示,但我想现在启用或禁用它:

<% =Html.TextBox("MyTextbox", Model.MyValuenew { id = "MyTextbox", @class = "MyClass" })%>

如果Model.IsMyTextboxEnabled()的返回值== true ,我希望输出以下内容:

<input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" />

如果它== false ,我希望它输出为:

<input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" disabled />

最干净的方法是什么?

5 个答案:

答案 0 :(得分:15)

这应该可以解决问题:

<%= Html.TextBox("MyTextbox", Model.MyValuenew,           
      (Model.IsMyTextboxEnabled() ? (object) new {id = "MyTextbox", @class = "MyClass"}
                                  : (object) new {id = "MyTextbox", @class = "MyClass", disabled="true" })) %>

答案 1 :(得分:3)

在您的助手中,您是否需要检查代码,在生成html时,只需检查bool,然后添加disabled属性或将其删除?

这是一个简单的例子,并没有很好的结构,但......

if (disabled)
return string.Format(CultureInfo.InvariantCulture, "<input type=text disabled/>", new object[] { HttpUtility.HtmlAttributeEncode(s), myTextBox });

这就是你问的问题吗?

编辑:

等等,我现在看到了。我认为您需要创建自己的帮助程序或扩展MVC文本框助手,以便您可以这样做。

或者我认为你可以这么做;

<%= Html.TextBox("mytextbox","", new { disabled="true" } %>

以上是未经测试的,但这样的事情应该有用。

编辑2:

<% if (condition) {%>
  <%= Html.TextBox("mytextbox", "", new {@readonly="readonly"}) %>
<%} else {%>
  <%= Html.TextBox("mytextbox", "") %>
<%}

答案 2 :(得分:3)

太晚了,但希望它会有所帮助:

我最近一直在使用ASP MVC(因为我拒绝为每个可能的属性集合使用匿名类型的一种组合)意识到,从MVC 2开始,每个Input Extension方法都有两种形式:一种具有属性作为对象,一个作为IDictionary<string, Object>元素。见the msdn API

所以,我最终编写了以下内容,我个人认为创建多个对象更加方便(实际上,对于多个选项或复选框控件,您只能使用一个Dictionary并随意添加或删除属性):

 <% 
  IDictionary<string, Object> radioAttrs = new Dictionary<string, Object>();
  radioAttrs.Add("class", "radioBot");
  if (Model.EnabledRegistro)
  {
      radioAttrs["onclick"] = "updateControlsForInfoNom(true)";
  } 
  else
  {
     radioAttrs["disabled"] = "disabled";
  }
  %>

  <%: Html.RadioButtonFor(model => model.Accion.calculoRegistro, "true", radioAttrs)%>
  ...

答案 3 :(得分:0)

请参阅我的答案:Disabled Textbox

答案 4 :(得分:0)

使用此方法,您可以根据需要提供多个属性

@Html.TextBox("mytextbox", new {}, new { @class = "myclass", disabled = "true" })