首页 > 代码库 > 使用jQuery异步传递Model到控制器方法,并异步返回错误信息

使用jQuery异步传递Model到控制器方法,并异步返回错误信息

需要通过jquery传递到控制器方法的Model为:

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; } 
    }
<style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style>

 

使用下面这个类的Message属性装载成功或错误信息,并最终转换成json格式返回给视图: 

    public class PersonVm
    {
        public string Message { get; set; } 
    }
<style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style>

 

控制器通过遍历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});
            }
        }    
 
<style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style>

 

视图使用 $.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=http://www.mamicode.com/"~/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>
}
 
<style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style>