我无法在我的视图中进行数据验证。我相信“资产名称”应该显示一条错误消息,如果用户选项卡进入文本框并且没有放入任何数据,但当文本框失去焦点时不会显示任何消息。
模型:
using System.ComponentModel.DataAnnotations;
namespace ACore.Models
{
public class AssetForm
{
[Required]
public string AssetName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
[UIHint("StatesEditor")]
public State State { get; set; }
[Required(ErrorMessage = "TEST")]
public string ZipCode { get; set; }
[Required]
public string Seg3Code { get; set; }
}
}
看法:
@using System.Web.Optimization
@model ACore.Models.AssetForm
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "frmAsset" }))
{
<div class="tempStyle">
<div class="editor-label fl">
@*@Html.LabelFor(model => model.AssetName)*@
Asset Name:
</div>
<div class="editor-field">
@Html.EditorFor(model => model.AssetName)
@Html.ValidationMessageFor(model => model.AssetName)
</div>
</div>
<div class="tempStyle">
<div class="editor-label">
Address 1:
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address1)
@Html.ValidationMessageFor(model => model.Address1)
</div>
</div>
}
Web.config 部分
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="true" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
我最终添加了下面的代码,但我班级中的 DataAnnotations 似乎与验证无关。我更愿意通过 DataAnnotations 控制验证:
// Validate the Maintenance and Office percentages.
var validator = $("#frmAsset").validate({
rules: {
AssetName: {
required: true
},
Seg3Code: {
required: true,
minlength: 3,
maxlength: 3
}
},
messages: {
AssetName: " ✖ Required",
Seg3Code: " ✖ Required"
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "/Asset/Create",
data: {
},
//data: $("form").serialize(),
success: function (data) {
//console.log(data);
// Close popup window
var window = $('#AssetEditorPopUp').data("kendoWindow");
window.close();
// Refresh grid to show changes
$('#grid').data("kendoGrid").dataSource.read();
},
error: function () {
alert("There was an error editing the asset.");
}
});
return false; // to block page redirect since you're using ajax
}