Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 793
user650922 Avatar asked Jul 07 '11 12:07

user650922


3 Answers

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);
like image 57
Jamie Dixon Avatar answered Sep 27 '22 19:09

Jamie Dixon


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)
like image 32
MurtuzaB Avatar answered Sep 27 '22 19:09

MurtuzaB


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)
}
like image 30
Treborbob Avatar answered Sep 27 '22 18:09

Treborbob