public class CityModel
{
public int Id { get; set; }
[display(Name = "City")]
[required(ErrorMessage = "City is required")]
public string City { get; set; }
}
并且控制器具有以下操作方法
public ActionResult City()
{
var cities = GetCities();
return View(cities);
}
[HttpPost]
public ActionResult SaveCity(CityModel cityModel)
{
if (ModelState.IsValid)
{
//Save City
return null;
}
else
{
return View();
}
}
public List<CityModel> GetCities()
{
var citiesList = new List<CityModel>
{
new CityModel() {Id = 1,City = "London"},new CityModel() {Id = 2,City = "New York"}
};
return citiesList;
}
这些观点有以下标记
@model List<CityModel>
<h2>Cities</h2>
@Html.ValidationSummary(true)
@using (@Html.BeginForm(null,null,FormMethod.Post,new { id = "frmSite",name = "frmSite" }))
{
@Html.EditorForModel()
<input type="submit" name="Sumbit" onclick=" SaveCity(); return false; " />
}
<script>
function SaveCity() {
$.ajax({
type: "POST",url: "/Home/SaveCity",contentType: "application/html; charset=utf-8",data: {
Id: $('.cityId').val(),City: $('.cityName').val()
},success: function (data) {
}
});
}
</script>
编辑器模板看起来像
@model CityModel
<table class="table">
<tr>
<td>
@Html.TextBoxFor(x => x.Id,new {@class = "cityId"})
</td>
</tr>
<tr>
<td>
@Html.TextBoxFor(x => x.City,new {@class = "cityName"})
@Html.ValidationMessageFor(x => x.City)
</td>
</tr>
</table>
我检查了< script src =“/ Scripts / jquery-1.10.2.js”>< / script> < script src =“/ Scripts / jquery.validate.js”>< / script> < script src =“/ Scripts / jquery.validate.unobtrusive.js”>< / script>包含在页面中< add key =“UnobtrusiveJavaScriptEnabled”value =“true”/>存在于Web配置文件中
解决方法
function SaveCity() {
$.validator.unobtrusive.parse($form);
$form.validate();
if ($form.valid()) {
$.ajax({
type: "POST",contentType:"application/json; charset=utf-8",City: $('.cityName').val()
},success: function (data) {
}
});
}
}
如果它纯粹是客户端,那么错误将包含在jquery验证对象$form.validate().errorList中,但你必须做一些类似于我在下面提到的手动处理.
如果希望返回服务器端模型状态,可以将模型状态错误添加为控制器中的键值对,并将它们作为json返回.
您可以使用以下方法显示消息.
这将查找带有模型状态错误键的所有验证消息跨度,并将红色错误消息添加到它们.请注意,您可能希望对此进行调整以显示针对某个键的许多错误消息.
public dovalidation(e)
{
if (e.data != null) {
$.each(e.data,function (key,value) {
$errorSpan = $("span[data-valmsg-for='" + key + "']");
$errorSpan.html("<span style='color:red'>" + value + "</span>");
$errorSpan.show();
});
}
}
更新
以上是上面的改编,所以你可以从jquery不显眼的错误中手动解析它:
$.each($form.validate().errorList,value) {
$errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
$errorSpan.html("<span style='color:red'>" + value.message + "</span>");
$errorSpan.show();
});
只要在其他声明中弹出它就可以了.
总结
以上是DEVMAX为你收集整理的Jquery post和unobtrusive ajax验证不工作mvc 4全部内容。
如果觉得DEVMAX网站内容还不错,欢迎将DEVMAX网站 推荐给好友。