Search code examples
asp.net-mvchtmlasp.net-mvc-5

How do I make EditorFor conditionally readonly?


I have this line of code:

@Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })

I have a variable in my view data dictionary called Readonly. How do I make Quantity read-only if ViewBag.Readonly is true and not read only if it is false?

Simple thing, but the combination of Razor with HTML (which is ancient) makes otherwise simple things impossible.

Edits:

I don't want to use an if statement. That is a last resort because it violates DRY which I have been severely burned many times in the past for not following.

The line I have above does work insofar as it makes the text box read-only. I need to make this conditional based upon my view state.

Solution:

I've used the following. It still is a DRY violation, but it reduces it to one line.

@Html.EditorFor(model => model.Quantity, new { htmlAttributes = ViewBag.Readonly ? (object)new { @class = "form-control", @readonly = "htmlsucks" } : (object)new { @class = "form-control" } })

Solution

  • Old question, but was looking at this today - so thought i'd add an answer anyway.

    The html helpers accept the html attributes as either an object or an IDictionary<string, object>.

    This means we can add code to construct the attributes to a variable and then pass that in.

    e.g.

    @{
        var htmlAttributes = new Dictionary<string, object>()
        {
            { "class", "form-control" }
        };
    
        if (ViewBag.Readonly) htmlAttributes.Add("readonly", "readonly");
    }
    
    @Html.EditorFor(model => model.Quantity, new { htmlAttributes = htmlAttributes })