1

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.

2
  • Are you using MVC-5.1+. If not you cannot pass html attributes to the default editor template (you will need to create your own custom EditorTemplate). Alternatively use @Html.TextBoxFor(m => m.Quantity, new { type = "number ", style = "width: 30px;" }) Commented Aug 13, 2015 at 2:24
  • 1
    Sure, I'll give you a few options. Commented Aug 13, 2015 at 2:32

1 Answer 1

2

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.

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.