我正在尝试利用 MVC 中的内置验证,但它似乎不起作用。如果我将表单中的字段留空,我会返回“成功保存”。信息。
不应该在表格中将“必填”字段标记为必填吗?
控制器:
public ActionResult Create([DataSourceRequest] DataSourceRequest request, ACore.Asset assetForm)
{
var results = new
{
value = false,
Message = ""
};
if (ModelState.IsValid)
{
results = new
{
value = true,
Message = "Successfully Saved."
};
return Json(results);
}
results = new
{
value = false,
Message = "Please check the form values."
};
return Json(results);
}
查看(精简):
@using (Html.BeginForm("Create", "Asset", FormMethod.Post, new { id = "frmAsset"}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="tempStyle">
<div class="editor-label fl">
@Html.LabelFor(model => model.AssetName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.AssetName)
@Html.ValidationMessageFor(model => model.AssetName)
</div>
</div>
<div style="position: relative;">
<input type="button" value="Save" id="btnSave" />
</div>
处理我的保存的 JavaScript:
var saveAsset = function (e) {
var form = $("#frmAsset");
$.ajax({
type: "POST",
url: "/Asset/Create",
data: $(form).serialize(),
success: function (data) {
if (data.value == true) {
alert(data.Message);
// Close popup window
var window = $('#AssetEditorPopUp').data("kendoWindow");
window.close();
// Refresh grid to show changes
$('#grid').data("kendoGrid").dataSource.read();
return;
}
alert(data.Message);
},
error: function () {
alert("There was an error editing the asset.");
}
});
};
模型:
public class Asset
{
[ScaffoldColumn(false)]
public int AssetId { get; set; }
[Required]
[Display(Name="Asset Name:")]
public string AssetName { get; set; }
public string AssetFormerName { get; set; }
public string Seg1Code { get; set; }
public string Seg3Code { get; set; }
public bool? ActiveFlag { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string AssetType { get; set; }
[Display(Name = "ZipCode:")]
[RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "Enter only alphabets and numbers of First Name")]
public string ZipCode { get; set; }
}
这就是我做 POST 而不是 ajax 的结果。