0

I want to change the class/style of my @Html.EditorFor field. I read something about customizing the template, but there is no template folder in my porject (Views/Shared/ONLY_FILES_HERE). Sadly I am NOT working with MVC 5.1.

Also I DON'T want to use TextBoxFor, because of inputvalidation.

How can I achieve this?

Here is a snippet of my model:

public class CreateTableColumnModels
{
    [RegularExpression(@"^[A-Za-z0-9]+$", ErrorMessage = "Use letters and numbers only please")]
    [Display(Name = "Name")]
    public string Name { get; set; }

I tried this:

@model QlikViewStammdaten.Models.CreateTableColumnModels
<div>
    @Html.EditorFor(x => Model.Name, new { @class = "form-control" })
</div>
13
  • Have tried with : @Html.EditorFor(x=> x.MyProperty, new { htmlAttributes = new { @class = "MyCssClass" } }) Commented Jul 17, 2018 at 8:26
  • 2
    Just create the Editor/DisplayTemplates folders inside Views/Shared folder and add a <classname>.cshtml Commented Jul 17, 2018 at 8:26
  • @PrashantPimpale yes, it's for >=MVC 5.1 Commented Jul 17, 2018 at 8:28
  • Take a look at :stackoverflow.com/a/4577748/7124761 Commented Jul 17, 2018 at 8:29
  • 1
    What is wrong with using TextBoxFor? (they ultimately call the same code anyway). And there is no issue with validation. Commented Jul 17, 2018 at 9:07

1 Answer 1

1

As already mentioned in the comments, it is better to add a class to Html.TextBoxFor and NOT @Html.EditorFor. Why? because @Html.EditorFor renders a template and that template could contain multiple controls (now to which one of those controls do you want to add the class?)... see Adding a class to EditorFor

If you want numeric type, then add @type = "number"

@Html.TextBoxFor(m => m.Name, new { @class = "form-control", @type = "number"  }) 

Note: it is not x => Model.Name but m => m.Name

I am sure you already know this, but [Display(Name = "Name")] is redundant in your model, as the default display name is the variable name itself.

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.