Domanda

Why does EditorFor renders different classes and input types for byte and short, as shown here:

<div class="form-group">
    <input class="text-box single-line" data-val="true" 
        data-val-number="The field Num Year / Period must be a number."
        id="NumYear_Period" name="NumYear_Period" type="number" value="" />
</div>

<div class="form-group">
    <input class="form-control" data-val="true" 
        data-val-number="The field Start Year must be a number." 
        id="Start_Year_Period" name="Start_Year_Period" type="text" value="" />
</div>

Where "NumYear_Period" is a Nullable Byte and "Start_Year_Period" is a Nullable Short as:

    [Display(Name = "Num Year / Period")]
    public Nullable<byte> NumYear_Period { get; set; }

    [Display(Name = "Start Year")]
    public Nullable<short> Start_Year_Period { get; set; }

The Create.cshtml view contains:

<div class="form-group">
    @Html.EditorFor(model => model.NumYear_Period)
</div>
<div class="form-group">
    @Html.EditorFor(model => model.Start_Year_Period)
</div>

I have no EditorTemplates present, so why!!

Using Bootstrap, Visual Studio 2013 Update 1, MVC 5.1.1, .Net 4.5, Razor 3.1.1

È stato utile?

Soluzione

It renders differently because there is no specific template for the type short or System.Int16 in the private collection of _defaultEditorActions defined in System.Web.Mvc.Html.TemplateHelpers. It has only defaults for:

    "HiddenInput",
    "MultilineText",
    "Password",
    "Text",
    "Collection",
    "PhoneNumber",
    "Url",
    "EmailAddress",
    "DateTime",
    "Date",
    "Time",
    typeof(byte).Name,
    typeof(sbyte).Name,
    typeof(int).Name,
    typeof(uint).Name,
    typeof(long).Name,
    typeof(ulong).Name,
    typeof(bool).Name,
    typeof(decimal).Name,
    typeof(string).Name,
    typeof(object).Name,

As you already stated that you have no EditorFor templates there is no otherway for the MVC framework to render a default input tag for you.

To have a specific renderig for a short datatype add a file Int16 to the EditorTemplates folder under your view folder or under the Shared folder with hte following content:

@model short

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @type = "number" }) 

This will render short types from your models as

<input ..... type="number" ... />

Alternatively you could decorate your model property with an UIHint like so:

[Display(Name = "Start Year")]
[UIHint("Int32")]
public Nullable<short> Start_Year_Period { get; set; }

which basically instructs the TemplateHelper to use the template for the int type (or System.Int32 in full)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top