【问题标题】:Ajax data not getting to controller? why?Ajax 数据没有到达控制器?为什么?
【发布时间】:2013-12-14 13:55:29
【问题描述】:

我正在使用 mvc4 应用程序。我使用 .cshtml 文件开发了一个表单,它继承了模型并具有相应的控制器操作。 我正在使用类似的 ajax jquery 提交表单,

          var body=$('#formId').serialize();
          $.ajax({
                url: submitAction,
                type: "POST",
                datatype: "json",
                data: body,
               success: function (data) {
               if (data != null) {
                 alert("success");
               }
               });

“body”很好,它已经序列化了数据,submitAction 是保存我的控制器动作的 var,并且控制被转移到那里。

编辑:

我的控制器看起来像,

    public JsonResult(ParentModel model) /*here model always hold null values, WHY??*/
    {
    //stmts..
    return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
    }

但是,我的控制器操作的参数显示空值。有人可以告诉我可能是什么错误,我该如何解决?

【问题讨论】:

    标签: javascript jquery ajax serialization controller


    【解决方案1】:
       $.ajax({
         url: submitAction,
         type: "POST", <-- you make post, but asp.net mvc controller receives default GET request
        data: { model: body},
    
    [HttpPost]
    public JsonResult(string model) //<--now you pass string and to Deserialize in ParentModel 
     {
       JavaScriptSerializer jss= new JavaScriptSerializer();
       ParentModel pmodel = jss.Deserialize<ParentModel >(model); 
    
       return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
     }
    

    尝试在您的请求中编辑data: 部分, 删除数据类型:“json”

    并将类型model参数编辑为字符串

    【讨论】:

    • 对不起,它没有任何区别。恐怕..;(
    • 它不起作用,因为它在反序列化时给出了无效 Json Primitive 的错误
    猜你喜欢
    • 2019-09-19
    • 2021-01-13
    • 2022-10-04
    • 2018-06-21
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多