整件事是,我希望能够在我自定义编写的 Ajax 代码上使用 MVC3 内置的客户端验证。(我说的是使用HTML.BeginForm()
&制作的表单中可用的验证Ajax.BeginForm()
)
我的模型如下所示:
public class BrandVewModel
{
public int ID { get; set; }
[Display(Name = "Brand Name")]
[Required(ErrorMessage = "Please fill in the blank!")]
[StringLength(40, ErrorMessage = "The name must not be more than 40 characters long!")]
public string Name { get; set; }
}
我的视图看起来像这样:
@using (Ajax.BeginForm("Insert_Brand", "Admin", FormMethod.Post, new AjaxOptions { UpdateTargetId = "result" }))
{
@Html.HiddenFor(model => model.ID)
@Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
<input value="Create" type="submit" name="Create New Brand" />
<div id="result"></div>
}
如您所见,我正在使用Ajax.BeginForm()
哪个好。显然,对于我的视图模型,如果用户将名称字段留空并单击提交按钮,他们将显示相应的错误,而不会将表单数据发送到服务器!(因为它是客户端,表单验证,感谢 jQuery)
但是我需要如下所示的简单表单,(而不是Ajax.BeginForm()
)并具有所有客户端验证功能:
<form method="post" action="@Html.Action("Insert_Brand","Admin")">
@Html.HiddenFor(model => model.ID)
@Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
<a onclick="CreateBrand()">Create Brand</a>
</form>
// honestly I have no idea what 'custom-written ajax coding', or what I do here is called :p
<script type="text/javascript" >
function CreateBrand() {
var item = { Brand: { Name:$('#Name').val()} };
$.ajax({
url: '/Admin/Insert_Brand',
type: "POST",
data: JSON.stringify(item),
dataType: "text json",
contentType: "application/json; charset=utf-8",
success: function (t) {
console.log(t);
$("#result").html(t);
return;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Failed!");
console.log("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
}
</script>
正如我所说,当我使用这种 ajax 表单发布时,我需要向用户显示所有好的验证消息。但我不知道我怎么能做到这一点......
有什么办法吗?