31

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" } })

8 Answers 8

33

EDIT: MVC 5

Controller

ViewBag.Readonly=true;//false

View

@Html.EditorFor(model => model.Quantity, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" }} : new { htmlAttributes = new { @class = "form-control" } })
3
  • 1
    Nice. I see how you minimized the DRY violation. I respect that. I've changed things a little but I think I'll use this. I still hope for a better options, but this works for now.
    – Jordan
    Commented Mar 20, 2015 at 18:29
  • 1
    This is the best answer
    – user4083514
    Commented Mar 22, 2015 at 16:12
  • 10
    the problem of this is when you have a large set of htmlAttributes, you have to repeat all the others just to switch the readonly??? And it's even worse when you have other attributes (similar to readonly) to switch together independently, such as disabled, required, ... So suppose the number of such attributes is n, you need 2^n expressions with duplicated settings for other attributes. That's a terrible design. The best design in this case is if the property is set to null, just ignore rendering it. ASP.NET MVC still need more improvement.
    – King King
    Commented Jun 8, 2017 at 1:50
6

It's very simple. Do it like this.

@if((bool)ViewBag.Readonly)
{
    @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
}
else
{
    @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
}
6
  • You can pass html attributes to Html.EditorFor in MVC5 (I should have been clearer about which version of MVC I am using.) The code I have above does make the text box read only. I do not know how to make that conditional without an if statement (again should have been clearer, sorry).
    – Jordan
    Commented Mar 19, 2015 at 19:32
  • Why don't you want to use an if statement?
    – ataravati
    Commented Mar 19, 2015 at 19:34
  • 1
    No problem. I have been burned in the past by not following the DRY principle. A single two part if statement with very simple content seems like no big deal, but it can grow as you modify code over time. I will do this if no other solution presents itself, but this just seems like a weakness in the speck not to be able to do this. HTML should use readonly='true|false' not this name-only attribute nonsense that they still have.
    – Jordan
    Commented Mar 19, 2015 at 19:37
  • 4
    And it is REALLY ugly code to have if statement's like that everywhere you want to do something as simple as make a field conditionally read-only. I like my code to be human readable. I may see if I can hack the integer template and do this myself to avoid that situation. I'll have to figure out how to do that. ...
    – Jordan
    Commented Mar 19, 2015 at 19:39
  • I agree that it's ugly. But, there's no other option. Unless, you want to use AngularJS, which I think is totally unnecessary if you want to use it for this purpose only.
    – ataravati
    Commented Mar 19, 2015 at 19:42
6

Today I had to deal with this issue as I had to dynamically set a "readonly" attribute to a Html.TextBoxFor element. I ended up writing the following helper method which allowed me to workaround the issue while keeping a DRY approach:

/// <summary>
/// Gets an object containing a htmlAttributes collection for any Razor HTML helper component,
/// supporting a static set (anonymous object) and/or a dynamic set (Dictionary)
/// </summary>
/// <param name="fixedHtmlAttributes">A fixed set of htmlAttributes (anonymous object)</param>
/// <param name="dynamicHtmlAttributes">A dynamic set of htmlAttributes (Dictionary)</param>
/// <returns>A collection of htmlAttributes including a merge of the given set(s)</returns>
public static IDictionary<string, object> GetHtmlAttributes(
    object fixedHtmlAttributes = null,
    IDictionary<string, object> dynamicHtmlAttributes = null
    )
{
    var rvd = (fixedHtmlAttributes == null)
        ? new RouteValueDictionary()
        : HtmlHelper.AnonymousObjectToHtmlAttributes(fixedHtmlAttributes);
    if (dynamicHtmlAttributes != null)
    {
        foreach (KeyValuePair<string, object> kvp in dynamicHtmlAttributes)
            rvd[kvp.Key] = kvp.Value;
    }
    return rvd;
}

It can be used in the following way:

var dic = new Dictionary<string,object>();
if (IsReadOnly()) dic.Add("readonly", "readonly");
Html.TextBoxFor(m => m.Name, GetHtmlAttributes(new { @class="someclass" }, dic))

The code is quite self-explanatory, however I also explained the underlying logic in this post on my blog.

3
  • Still fairly ugly razor code, but I can work with this. Thanks, Instead of a dictionary I would probably create a translation layer that would change readonly=true to readonly="readonly" and remove readonly=false so that read-only could be set to a Boolean value. Stupid HTML spec with your valueless attributes! This is why we normalize interfaces. I wish I could go back in time and slap somebody sometimes.
    – Jordan
    Commented Nov 14, 2018 at 16:16
  • @Jordan , the main advantage of this workaround is that it can also be used to dinamically set other property-setting and/or valued attributes (including, yet not limiting to, readonly).
    – Darkseal
    Commented Nov 14, 2018 at 17:38
  • Right, but the problem with the OP was with with valueless attributes which is rather small set. The only ones I can think of are readonly and disabled. These are the only real problems if you think about it. They are the only attributes that you cannot just leave blank.
    – Jordan
    Commented Nov 14, 2018 at 20:04
2

In case you have many places in your view with such logic, I think using the library FluentDataAnnotations can keep you code clean and clear.

If you are familiar with FluentValidator, it's very similar using.

In your case all the logic will moved from a view to model annotation class. In you will have only @Html.EditorFor(model => model.Quantity)

It even allows to use model properties in conditions e.g. this.When(model => !model.AllowEditPhone, () => { this.For(m => m.Phone).SetReadOnly(false); });

Here the NuGet package that requires ASP.NET MVC 5. (Support for ASP.NET Core are in progress.)

1

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 })    
1
  • How would you add more htmlAttributes to the next field that also needs to be readonly?
    – Mahogany
    Commented Jun 27 at 17:02
1

By writing a helper method the DRY principal can be respected.

    using System.Web.Mvc.Html;

    public static MvcHtmlString Concat(this MvcHtmlString first, params MvcHtmlString[] strings)
    {
        return MvcHtmlString.Create(first.ToString() + string.Concat(strings.Select(s => ( s == null ? "" : s.ToString()))));
    }

    public static MvcHtmlString ConditionalEditFor<TModel,TValue>(this HtmlHelper<TModel> helper, bool EditCondition, Expression<Func<TModel, TValue>> Expression)
    {
        helper.ConditionalEditFor(EditCondition,Expression,false);
    }

    public static MvcHtmlString ConditionalEditFor<TModel, TValue>(this HtmlHelper<TModel> helper, bool EditCondition, Expression<Func<TModel, TValue>> Expression, bool IncludeValidationOnEdit)
    {
        if (EditCondition)
        {
            if (!IncludeValidationOnEdit)
                return EditorExtensions.EditorFor<TModel, TValue>(helper, Expression);
            else
                return EditorExtensions.EditorFor<TModel, TValue>(helper, Expression).Concat(ValidationExtensions.ValidationMessageFor<TModel, TValue>(helper, Expression));
        }
        else
        {
            return DisplayExtensions.DisplayFor<TModel, TValue>(helper, Expression);
        }
    }

then in your view:

add a conditional statement to determine readonly e.g.

@{bool IsReadOnly = YourCondition;}

@Html.ConditionalEditFor(!IsReadOnly/*condition*/, model => model.YourProperty,true /*do validation*/)

you can then add whatever other overrides you want.

1

JQUERY to read SETUP_TYPE control value and disable controls with a particular CSS selector.

$(function () {
    if ($("#SETUP_TYPE").val() == "1") { $('.XXX').attr('disabled', true); }
})

$(function () {
    if ($("#SETUP_TYPE").val() == "2") { $('.YYY').attr('disabled', true); }
})

This control is disabled if SETUP_TYPE is 1 or 2.

@Html.EditorFor(model => model.CLAIM, new { htmlAttributes = new { @class = "form-control XXX YYY" } })

This control is disabled if SETUP_TYPE is 1.

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

This control is disabled if SETUP_TYPE is 2.

@Html.EditorFor(model => model.INSURED, new { htmlAttributes = new { @class = "form-control YYY" } })
0

You can write a an IHtmlHelper extension with additional parameters:

public static IHtmlContent ReadonlyishTextBoxFor<TModel, TProperty>(this IHtmlHelper<TModel> helper,
    Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null, bool shouldBeReadonly = false)
{
    var attributes = new Dictionary<string, object>();
    if (htmlAttributes != null)
    {
        foreach (var propertyInfo in htmlAttributes.GetType().GetProperties())
        {
            attributes.Add(propertyInfo.Name, propertyInfo.GetValue(htmlAttributes));
        }
    }

    if (shouldBeReadonly)
    {
        attributes.Add("readonly", "readonly");
    }

    return helper.TextBoxFor(expression, format: null, attributes);
}

Razor:

@Html.ReadonlyishTextBoxFor(p => p.Email, new { @class = "form-control" }, true )
@Html.ReadonlyishTextBoxFor(p => p.Email, new { @class = "form-control" } )

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.