【问题标题】:JsonResult takes only the first parameter and ignores the restJsonResult 只接受第一个参数,忽略其余参数
【发布时间】:2023-03-19 19:54:01
【问题描述】:

我遇到了一个超出我水平的奇怪问题,我试图解决这个问题但没有运气。

我正在开发一个简单的 MVC 应用程序,并且我正在使用 ajax 将数据从视图发送到控制器。由于某种原因,控制器只识别了第一个参数,其余的只是空值。我什至尝试放置固定字符串而不是变量,但它们在控制器中仍然显示为空???

观点:

  $.ajax({
        type: "POST",
        url: "../Home/AddItem",
        data: "{ItemModel: 'ttt1', ItemName: 'ttt2'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(JSON.stringify(data));
            if (data.Success == "Success") {
                alert("Item has been added.");
            } else {
                alert("We were not able to create the offer");
            }
        },
        error: function (exception) {                
            console.log(exception);
        }
    });

在 Home 控制器上,我有以下操作:

[HttpPost]
    public JsonResult AddItem(string ItemModel, string ItemName)//ItemName is always null??
    {
        try
        {
            _DB.Database.ExecuteSqlCommand(@"INSERT INTO ITEMS(iModel, iName) VALUES ({0}, {1})", ItemModel, ItemName);
            return Json(new { Success = "Success" });
        }
        catch (Exception ex)
        {
            throw ex;
        }            
    }

【问题讨论】:

    标签: javascript c# json asp.net-mvc


    【解决方案1】:

    您没有正确发送数据。

    代码指示 JSON,但仅发送一个字符串。如果你检查ItemModel,我确定它会包含客户端发送的字符串数据。

    创建一个 JavaScript 对象,然后将其字符串化为请求的主体。

    var payload = { ItemModel: 'ttt1', ItemName: 'ttt2' }; //<-- create object
    $.ajax({
        type: "POST",
        url: "../Home/AddItem",
        data: JSON.stringify(payload), //<-- properly format for request
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(JSON.stringify(data));
            if (data.Success == "Success") {
                alert("Item has been added.");
            } else {
                alert("We were not able to create the offer");
            }
        },
        error: function (exception) {                
            console.log(exception);
        }
    });
    

    然后模型绑定器应该能够区分所需的参数。

    理想情况下,当期望请求正文中包含数据时,最好使用模型

    public class Item {
        public string ItemModel { get; set; }
        public string ItemName { get; set; }
    }
    

    并让操作使用FromBody 属性在请求正文中显式查找它

    [HttpPost]
    public JsonResult AddItem([FromBody]Item item) {
        if(ModelState.IsValid) {
            try {
                var sql = @"INSERT INTO ITEMS(iModel, iName) VALUES ({0}, {1})";
                _DB.Database.ExecuteSqlCommand(sql, item.ItemModel, item.ItemName);
                return Json(new { Success = "Success" });
            } catch (Exception ex) {
                throw ex;
            }
        }
        return Json(new { Success = "BadRequest" });         
    }
    

    【讨论】:

    • 谢谢,我会尝试一下,稍后再回复您。
    • 没用,我也一样,第二个参数为null??我没有想法,但我会继续努力
    • 非常感谢,我遇到了最奇怪的问题...我已经删除了控制器方法并从头开始编写了一个新方法,并且它有效。新的控制器方法名称不同但内容完全相同!我对此没有任何解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    相关资源
    最近更新 更多