3

为什么 EditorFor 会为 byte 和 short 呈现不同的类和输入类型,如下所示:

<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>

其中“NumYear_Period”是一个可空字节,“Start_Year_Period”是一个可空短,如下:

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

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

Create.cshtml 视图包含:

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

我没有 EditorTemplates,所以为什么!!

使用引导、Visual Studio 2013 更新 1、MVC 5.1.1、.Net 4.5、Razor 3.1.1

4

1 回答 1

2

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)

于 2014-06-27T17:03:35.130 回答