1

That is a tricky question because I want to add Html Attributes to the EditorFor() but do not want to replace the ones that was already created. Let me explain:

I have a default Editor Template for string.cshtml with the following code:

@{    
    var htmlAttributes = ViewData;
    htmlAttributes["class"] = "text-box single-line form-control";
    htmlAttributes["placeholder"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
    htmlAttributes["title"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
}
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, htmlAttributes)

It is used to always add the following class, placeholder and title, based on the DisplayName DataAnnotation, for the Form Inputs, it is quite handy!

But the problem is that I'm having trouble adding the disable attribute for one specific Form Input with the common code:

@Html.EditorFor(x => x.Field, new { htmlAttributes = new { disabled = "" } })

When the Form Input is with a field that is not a string, it will not follow the created EditorTemplate and it will work with this exactly code, but when it is a string, the EditorTemplate replaces the Html Attributes.

Does anyone has any clue on this?

3
  • You need to either use an EditorTemplate or use TextBoxFor instead. Commented Aug 19, 2014 at 19:14
  • Turns out, the way of creating the html attributes on the EditorFor was wrong, when I changed to this it all works: @Html.EditorFor(x => x.Field, new { @disabled = "" }) Commented Aug 19, 2014 at 20:44
  • The model in the edit template should be deciding this sort of thing. Commented Aug 19, 2014 at 20:46

1 Answer 1

2

Turns out there was a few dumb errors, first of all the declaration on the EditorFor() field was wrong, the correct one is this:

@Html.EditorFor(x => x.Field, new { @disabled = "" })

The second point is to keep using the incoming htmlAttributes in the string.cshtml EditorTemplate, replacing the class property definition:

htmlAttributes["class"] = "text-box single-line form-control";

For:

htmlAttributes["class"] = htmlAttributes["class"] + "text-box single-line form-control";

In this way, the incoming html attributes is just concatenated with the new default ones.

Sign up to request clarification or add additional context in comments.

Comments

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.