How to set a textbox readonly property true or false
I need your help in creating a textbox readonly property true or false based on a condition. I tried however was unsuccessful. 开发者_如何学编程Below is my sample code:
string property= "";
if(x=true)
{
property="true"
}
@Html.TextBoxFor(model => model.Name, new { @readonly = property})
My question is: Even though the condition is false I am unable to write or edit the textbox?
This is because the readonly
attribute in HTML is designed so that it's mere presence indicates a readonly textbox.
I believe that the values true|false
are completely ignored by the attribute and infact the recomended value is readonly="readonly"
.
To re-enable the textbox you'll need to get rid of the readonly
attribute altogether.
Given that the htmlAttributes
property of TextBoxFor
is an IDictionary
, you could simply build the object based on your requirements.
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)
A shorthand way to add the custom attrbute could be:
var customHTMLAttributes = (x)? new Dictionary<string,object>{{"readonly","readonly"}}
: null;
or simply:
@Html.TextBoxFor(model => model.Name, (x)? new {"readonly","readonly"} : null);
I achieved it using some extension methods
public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
{
string rawstring = htmlString.ToString();
if (disabled)
{
rawstring = rawstring.Insert(rawstring.Length - 2, "disabled=\"disabled\"");
}
return new MvcHtmlString(rawstring);
}
public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
{
string rawstring = htmlString.ToString();
if (@readonly)
{
rawstring = rawstring.Insert(rawstring.Length - 2, "readonly=\"readonly\"");
}
return new MvcHtmlString(rawstring);
}
and then....
@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsReadonly(x)
You probably need to refactor your code to be something along the lines of
if(x)
{
@Html.TextBoxFor(model => model.Name, new { @readonly = "readonly"})
}
else
{
@Html.TextBoxFor(model => model.Name)
}
精彩评论