asp.net-mvc - 如何使输入字段仅允许使用 EF 和数据注释的数字?

标签 asp.net-mvc entity-framework data-annotations

我想弄清楚是否有办法确保使用数据注释和 Entity Framework 只允许输入数字。

我正在使用以下代码

[Required]
[DisplayName("Client No")]
[Column("client_no", TypeName = "smallint")]
public virtual Int16 Number { get; set; }

我希望使用数字类显示它。

在一个地方,我使用以下内容
<input type="number" name="searchClientNo" class="numericOnly" /><br />

但在我使用的参赛表格中
@Html.EditorFor(m => m.Number, EditorTemplate.TextBox)

我有一个带有以下代码的定制 EditorFor
<div class="editor-label">
    @Html.Label((ViewData.ModelMetadata.DisplayName??ViewData.ModelMetadata.PropertyName),
        new Dictionary<string, object>
            {
                { "for", ViewData.ModelMetadata.PropertyName }
            })
</div>
<div class="editor-field">
    @Html.TextBox("", (object)Model,
        new Dictionary<string, object>
            {
                { "id", ViewData.ModelMetadata.PropertyName },
                { "name", ViewData.ModelMetadata.PropertyName },
                { "class", "text-box single-line"},
                { "data-bind", "value: " + ViewData.ModelMetadata.PropertyName },
            })
    @Html.ValidationMessage(ViewData.ModelMetadata.PropertyName,
        new Dictionary<string, object>
            {
                { "data-valmsg-for", ViewData.ModelMetadata.PropertyName }
            })
</div>

我想知道如何在不更改的情况下保留此代码但仍使用仅数字文本框。我需要使用 UIHint 吗?

或者,是否可以使我现有的 EditorFor 更智能?

我找到了这篇博文 http://robseder.wordpress.com/2012/06/01/uihint-displaytemplates-and-editortemplates-in-mvc/但我已经在使用自定义 EditorFor。可能我需要添加一个新类型,比如 EditorTemplate.NumericTextBox 并添加另一个编辑器?这听起来可能有用,我明天要试试这个......

非常感谢。

最佳答案

您可以编写自定义编辑器模板 ~/Views/Shared/EditorTemplates/NumberTemplate.cshtml :

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

然后用 UIHint 装饰你的 View 模型属性属性:
[Required]
[DisplayName("Client No")]
[Column("client_no", TypeName = "smallint")]
[UIHint("NumberTemplate")]
public virtual Int16 Number { get; set; }

在你的观点中:
@Html.EditorFor(x => x.Number)

或者如果您不想使用 UIHint您可以定义 View 模型上的属性 EditorTemplate.NumericTextBox = "NumberTemplate"进而:
@Html.EditorFor(m => m.Number, EditorTemplate.NumericTextBox)

关于asp.net-mvc - 如何使输入字段仅允许使用 EF 和数据注释的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13984602/

相关文章:

c# - 为什么 Database.Log 不是一个事件?

sql-server - 使用 Entity Framework 将数据导入和导出到 excel for asp.net mvc

servicestack - Servicestack References 与 ForeignKey 中的数据注释

c# - 如何在 Html.TextBoxFor 中格式化 DateTimeOffset?

c# - MVC C# - 多个 AbstractValidator<T> 的 FluentValidation 复合验证器

c# - 如何使用 Entity Framework 使用外键保存新记录?

c# - 在代码中将凭据(用户名/密码)分配给 EF

c# - 我如何在 ASP.NET MVC 6 (六) 代码中获取 bin 或 wwwroot 目录

c# - 确定何时在 .NET MVC 请求中发送无效的 JSON 键/值对

c# - 多个正则表达式数据注释验证