Asp.net-Mvc
如何使輸入欄位僅允許使用 EF 和數據註釋的數字?
我試圖弄清楚是否有辦法確保使用數據註釋和實體框架只允許數字輸入。
我正在使用以下程式碼
[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屬性:[Required] [DisplayName("Client No")] [Column("client_no", TypeName = "smallint")] [UIHint("NumberTemplate")] public virtual Int16 Number { get; set; }在你的視野內:
@Html.EditorFor(x => x.Number)或者如果您不想
UIHint在視圖模型上使用該屬性,您可以定義EditorTemplate.NumericTextBox = "NumberTemplate"然後:@Html.EditorFor(m => m.Number, EditorTemplate.NumericTextBox)