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;
}
The views have the following mark ups
@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>
And the editor template looks like
@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>
I have checked the <script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
are included in the page and <add key="UnobtrusiveJavaScriptEnabled" value="true" />
is present in the web config file
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…