JsonResult仅采用第一个参数,而忽略其余参数

时间:2018-10-17 16:21:05

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

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

我正在开发一个简单的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;
        }            
    }

1 个答案:

答案 0 :(得分:0)

您没有正确发送数据。

该代码表示​​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" });         
}