使用jQuery异步传递Model到控制器方法,并异步返回错误信息
时间:2014-05-14 13:35:35
收藏:0
阅读:449
需要通过jquery传递到控制器方法的Model为:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
使用下面这个类的Message属性装载成功或错误信息,并最终转换成json格式返回给视图:
public class PersonVm
{
public string Message { get; set; }
}
控制器通过遍历ModelState.Keys来显示错误信息。
public ActionResult Demo()
{
return View();
}
[HttpPost]
public ActionResult SavePerson(Person person)
{
if (ModelState.IsValid)
{
string message = string.Format("用户姓名:{0},年龄:{1}", person.Name, person.Age);
return Json(new PersonVm() {Message = message});
}
else
{
string errorMessage = "<div class=\"validation-summary-errors\">发生以下错误:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li class=\"field-validation-error\">"+error.ErrorMessage+"</li>";
}
}
errorMessage += "</ul>";
return Json(new PersonVm() {Message = errorMessage});
}
}
视图使用
$.toJSON()方法,把Model转换成json格式传递给控制器方法。把对象转换成json格式的jQuery扩展,在这里。
@model MvcApplication1.Models.Person
@{
ViewBag.Title = "Demo";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.EditorForModel()
<input type="submit" value="保存" id="personCreate"/>
<div>
<span id="resultMessage"></span>
</div>
@section scripts
{
<script src="~/Scripts/json.js"></script>
<script type="text/javascript">
$(function() {
$(‘#personCreate‘).click(function() {
var person = getPerson();
if (person == null) {
alert("用户名不能为空");
return;
}
var json = $.toJSON(person);
$.ajax({
url: ‘@Url.Action("SavePerson","Home")‘,
type: ‘POST‘,
dataType: ‘json‘,
data: json,
contentType: ‘application/json; charset=utf-8‘,
success: function(data) {
var message = data.Message;
$("#resultMessage").html(message);
}
});
});
});
function getPerson() {
var name = $(‘#Name‘).val();
var age = $(‘#Age‘).val();
return (name == "") ? null : { Name: name, Age: age };
}
</script>
}
评论(0)