【问题标题】:HTTP Methods GET (works) vs POST (does not work)HTTP 方法 GET(有效)与 POST(无效)
【发布时间】:2020-05-22 09:52:21
【问题描述】:

描述

使用触发器,我调用了一个函数,该函数检索局部视图并将其放入代码中的位置 (作品)

我调用这个函数来显示表格

function getTable() {

    var test= t6est;
    var test2test= edhwbtest;;

    if (test!= null && test2test!= null) {


        var testFtT= daysInMonth(test, test2test);

        $.ajax({

            url: "@Url.Action("PartialTabelaEcp", "Home")",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            dataType: "html",
            data: { testFtT: testFtT, test: test, test2test: test2test},
            cache: false,
            success: function (data) {
                $("#kartaEcp").html(data);
            },
            failure: function (error) {
                alert(error);

            },
            error: function (error) {
                alert(error);
            }
        });

    }

}

还有这个控制器:

[HttpGet]
        public ActionResult PartialTabelaEcp(int testFtT, int test, int test2test)
        { 
             return PartialView("_TabelaEwidencja");
        }
  • 我需要从httpget改为httpppost,因为我需要将数据发送到数据库

但是当我改变时

$.ajax({


            type: "GET",


and 


[HttpGet]
        public ActionResult

$.ajax({


            type: "POST",

and

[HttpPost]
        public ActionResult

错误

加载资源失败:服务器响应状态为 500(内部服务器错误)

【问题讨论】:

  • 是否有关于该错误的更多详细信息(如果您在本地运行,请打开详细错误)。您能否在[HttpPost] 操作中添加断点以查看它是否被击中。 500 表示该动作正在被击中,但之后的某些东西正在破坏它。

标签: c# asp.net ajax asp.net-mvc asp.net-core


【解决方案1】:

您的AJAX 电话如下所示:

  var json = {
          testFtT: testFtT ,
          test: test,
          test2test: test2test
         };

  $.ajax({
      type: "post",
      dataType: "json",
      data: {"json": JSON.stringify(json)},,
      url: "@Url.Action("PartialTabelaEcp", "Home")",
      cache: false,
      success: function (data) {
            $("#kartaEcp").html(data);
        },
      failure: function (error) {
            alert(error);

        },
      error: function (error) {
            alert(error);
        }
    });

您的Controller 方法将是:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult PartialTabelaEcp(string json)
{

  var serializer = new JavaScriptSerializer();
  dynamic jsondata = serializer.Deserialize(json, typeof(object));

  //Get your variables here from AJAX call
  var testFtT= jsondata["testFtT"];
  var test= jsondata["test"];
  var test2test= jsondata["test2test"];

  return PartialView("_TabelaEwidencja");
}

【讨论】:

  • serializer.Deserialize(json, typeof(object)); ||错误naer反序列化[不获取下一个数字参数“2”]
  • @krolPodGora 在调试过程中,您在Controller 方法中的json 字符串中得到了哪些值?确保您在js 端正确生成值
  • dataType: "json" ,?我得到一个 html 视图,所以我想我必须在那里有“html”?
  • @krolPodGora 不,因为您以json 格式发送到服务器,所以它应该是 json。你得到的输出是html,所以你可以在你的函数中相应地处理它。
  • 我已经使用 JsonConvert.DeserializeObject (json);
猜你喜欢
  • 2017-10-16
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多