MVC的前端和後端的Model Binding

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.