码迷,mamicode.com
首页 > Web开发 > 详细

MVC的前端和后端的Model Binding

时间:2018-08-28 20:21:53      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:for   ati   div   console   arp   直接   success   title   gear   

1.前端提交JSON 字符串

{"id":13,"title":"这里是标题33","day":"2018-8-16","status":0,"arr":[{"type":"r","quest":"333","q1":"3","q2":"3","q3":"3"},{"type":"c","quest":"444","q1":"4","q2":"4","q3":"4"},{"type":"t","quest":"5"}]}
            $.ajax({
                url: "/survey/post",
                method:"post",
                data: json,
                contentType: "application/json",
                success: function (data) {
                    console.log(data.status);
                }
            })  

后端MVC controller ( version<=5) , 如果是WebAPI, 则要加上[FromBody]修饰参数

    public class SurveyDTO
    {
        public string id { get; set; }
        public string title { get; set; }
        public DateTime day { get; set; }
        public string status { get; set; }
        public SurveyItem[] arr { get; set; }
    }
    public class SurveyItem {
        public string type { get; set; }
        public string quest { get; set; }
        public string q1 { get; set; }
        public string q2 { get; set; }
        public string q3 { get; set; }
    }
        [HttpPost]
        public ActionResult Post(SurveyDTO data)
        {}

JSON带有数组的话, 通常不能直接用EntityFramework的实体.要重新定义.

2. 前端使用表单提交

$.post(‘/survey/postForm‘, $(‘#form‘).serialize(), function (json) {
            if (json.isSuccess) {
               
            }

        });

$.ajax({
url: "/survey/postForm",
method: "post",
data: "id=" + key + "&title=" + title + "&day=" + date + "&status=" + sta + "&arr=" + JSON.stringify(this.storageArr),
success: function (data) {
console.log(data.status);
}
})

 

后端使用Formcollection 接受参数 

        [HttpPost]
        public ActionResult Post(FormCollection form)
        {
            var json = new { status = 0 };
            return Json(json);

        }

  

MVC的前端和后端的Model Binding

标签:for   ati   div   console   arp   直接   success   title   gear   

原文地址:https://www.cnblogs.com/zitjubiz/p/9550130.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!