如何设置文本框readonly属性true或false

use*_*922 5 c# asp.net-mvc-3

我需要你的帮助,根据条件创建一个文本框readonly属性true或false.然而我尝试了却没有成功.以下是我的示例代码:

string property= "";
if(x=true)
{
     property="true"
}
@Html.TextBoxFor(model => model.Name, new { @readonly = property})
Run Code Online (Sandbox Code Playgroud)

我的问题是:即使条件是假的,我也无法编写或编辑文本框?

Jam*_*xon 9

这是因为readonlyHTML中的属性被设计为仅仅存在表示只读文本框.

我相信true|false属性完全忽略了这些值,实际上是推荐值readonly="readonly".

要重新启用文本框,您需要readonly完全删除该属性.

鉴于htmlAttributes属性TextBoxForIDictionary,您可以根据您的要求简单地构建对象.

IDictionary customHTMLAttributes = new Dictionary<string, object>();

if(x == true) 
   // Notice here that i'm using == not =. 
   // This is because I'm testing the value of x, not setting the value of x.
   // You could also simplfy this with if(x).
{
customHTMLAttributes.Add("readonly","readonly");
}

@Html.TextBoxFor(model => model.Name, customHTMLAttributes)
Run Code Online (Sandbox Code Playgroud)

添加自定义属性的简便方法可以是:

var customHTMLAttributes = (x)? new Dictionary<string,object>{{"readonly","readonly"}} 
                                                          : null;
Run Code Online (Sandbox Code Playgroud)

或者干脆:

@Html.TextBoxFor(model => model.Name, (x)? new {"readonly","readonly"} : null);
Run Code Online (Sandbox Code Playgroud)