Can I change the width of an EditorFor with data annotations?

3.7k views Asked by At

There's a few questions on similar topics. However, they don't actually address my issue.

DisplayFormat for TextBoxFor in MVC

Display a formatted date in an EditorFor()

ASP.NET MVC EditorFor DateTime

I've been searching and reading up and cannot find an answer to this.

I'm currently using this to format my input box:

@Html.TextBoxFor(modelItem => item.Quantity, new { style = "width: 30px;" })

From my model, I have the brief data annotation:

[Required, Range(1, 100)]
public int Quantity { get; set; }

So I get this:

enter image description here

When I use

@Html.EditorFor(modelItem => item.Quantity, new { style = "width: 30px;" })

I get this:

enter image description here

What I want is the scroll, but to format the width.

I'm wondering, is there a way to format the width of an EditorFor with data annotations? If not, what is the easiest way to make such a format, to avoid repetition.. bootstrap, css? I'm not happy with the inline styling.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

From the comments, your using MVC-4. You cannot pass html attributes to the EditorFor() method unless your using MVC-5.1 or higher (refer the release notes - the section on Bootstrap support for editor templates)

One option is to use the TextBoxFor() method and pass type="number" to render the browsers numeric control

@Html.TextBoxFor(m => m.Quantity, new { type = "number ", style = "width: 30px;" })

Another would be to create a custom EditorTemplate (say _NumericControl.cshtml)

@model System.Int32
@Html.TextBoxFor(m => m, new { type = "number ", style = "width: 30px;" })

and call it using @Html.EditorFor(m => m.Quantity, "_NumericControl")

but this would really only be of any real benefit if the template were also to include other html elements, for example @Html.LabelFor(m => m) and @Html.ValidationMessageFor(m => m) and perhaps even the associated button so that the EditorFor() method renders all elements.