Search code examples
c#htmlrazoreditorfor

Html.EditorFor adding .textbox to element name


I have a project which contains a simple form for collecting signup info. Recently I have been working to add localization to the project, as all of the text shown to the user was hardcoded. I'm not sure what changed, but for some reason, now when Razor renders an HTML element using the Html.EditorFor method that ends up being a textbox, the Name property of the element has ".textbox" appended to it.

This breaks the bindings, so that when I receive my model all of the text values are null. Here is an example of what I'm seeing, Razor code:

<div class="form-group" ng-class="{ 'has-error': validate && accountForm.FirstName.$invalid }">
        @Html.LabelFor(m => m.FirstName, new { @class = @ViewBag.LabelCssRequired })
        <div class="@ViewBag.TextboxCss">
            @Html.EditorFor(m => m.FirstName, new { htmlAttributes = new { ng_model = "firstName" } })
        </div>
    </div>

and here is the rendered output:

<input class="text-box single-line form-control ng-valid-maxlength ng-not-empty ng-dirty ng-valid-parse ng-valid ng-valid-required ng-touched" id="FirstName_textbox" maxlength="100" name="FirstName.textbox" ng-model="firstName" required="required" type="text" value="">

It is also adding a "_textbox" to the id, but I'm not as concerned about that at the moment. For some reason, this only seems to be happening to input elements where the type is "text". I have another input generated with.EditorFor which has the type of email and it doesn't have any modifications to the name.

This behavior also seems to be restricted to Html.EditorFor, if I use.TextboxFor, it works fine.

I have been able to make the bindings work by explicitly setting the @Name property in Razor, but this only masks the symptom, and I would like to avoid having to do this for every text input on the site.

Has anyone seen this behavior before, or know of a fix?


Solution

  • By default, the TextBoxFor helper generates HTML using a built-in template. You can override the defaults by creating files in the project root\views\shared\editortemplates folder.

    Therefore the problem can be caused by some custom template being present there. Normally, you need to check for files whose name Match either the datatype (such as string) or the control type (such as TextArea). If the corresponding model property has a UIHint attribute on it, a custom file specified in it can also come into play.