Jquery 帖子和不显眼的 ajax 验证不起作用 mvc 4 [英] Jquery post and unobtrusive ajax validation not working mvc 4
本文介绍了Jquery 帖子和不显眼的 ajax 验证不起作用 mvc 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 jquery 回发上,如果模型状态无效,我想使用 jquery 非侵入式验证显示验证错误消息.我创建了一个示例应用程序.应用中的viewmodel如下
On the jquery postback if the model state is invalid I want to show the validation error messages using jquery unobtrusive validation. I have created a sample application. The viewmodel in the application is as below
public class CityModel
{
public int Id { get; set; }
[Display(Name = "City")]
[Required(ErrorMessage = "City is required")]
public string City { get; set; }
}
并且控制器有以下动作方法
and the controller has the following action methods
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, null, new {@class = "cityName"})
@Html.ValidationMessageFor(x => x.City)
</td>
</tr>
</table>
我已经检查了