我有这样一个简单的 ASP.NET MVC 动作:
public ActionResult Edit(EditPostViewModel data)
{
}
The EditPostViewModel
have validation attributes like this :
[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }
在视图中,我使用了以下辅助工具:
@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })
如果我做一个表格,这个文本框放在一个验证将首先在客户端,然后在服务(ModelState.IsValid
)完成提交。
Now I got a couple of questions :
Can this be used with jQuery ajax submit instead? What I am doing is simply remove the form and on clicking the submit button a javascript will gather data and then run the $.ajax
.
服务器端 ModelState.IsValid
能正常工作吗?
如何将验证问题转发给客户机,并将其显示为使用 build int 验证(@Html.ValidationSummary(true)
) ?
Ajax 调用示例:
function SendPost(actionPath) {
$.ajax({
url: actionPath,
type: 'POST',
dataType: 'json',
data:
{
Text: $('#EditPostViewModel_Text').val(),
Title: $('#EditPostViewModel_Title').val()
},
success: function (data) {
alert('success');
},
error: function () {
alert('error');
}
});
}
编辑1:
页面内容:
<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>