0

In my MVC Application View I have @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @readonly = "readonly" })

I need to remove the readonly-attribute when an if-statement occurs in my Controller. How can I, from the Controller, remove the attribute in the View, or add the attribute if I first remove it from the View and then change my if-statement?

1 Answer 1

2

I understand that you want to conditionally add the readonly attribute to a textbox.

You may use ViewData for that, from your controller assign ViewData["IsEmailReadOnly"] to a boolean value

if(MyCondition())
    ViewData["IsEmailReadOnly"] = true;
else
    ViewData["IsEmailReadOnly"] = false;

And then inside your View:

@{
    object textBoxAttrs;
    if((bool) ViewData["IsEmailReadOnly"]) {
        textBoxAttrs = new { @class = "form-control", @readonly = "readonly" };
    }
    else
    {
        textBoxAttrs = new { @class = "form-control" };
    }
}

@Html.TextBoxFor(m => m.Email, textBoxAttrs)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for answering! I'm getting the "Property or indexer 'ViewDataDictionary.Is Read Only' cannot be assigned to -- it is read only.
I'm sorry, change the property name, IsReadOnly could be already implemented in ViewDataDictionary. I'm updating the answer.
Not sure if I understand how ViewData works, but no i get the message: 'ViewDataDictionary' does not contain a definition for 'IsEmailReadOnly' and no extension method 'IsEmailReadOnly' accepting a first argument of type 'ViewDataDictionary' could be found (are you missing a using directive or an assembly reference?)
Sorry for the mistake, I didn't had time to check myself. ViewData must be accessed like any dictionary. The answer is not corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.