jquery - Ajax 向 Controller 操作发送空参数

标签 jquery json ajax asp.net-mvc

我想在 Asp.Net MVC 中通过 Ajax 提交页面输入。

JQuery Ajax json 数据不为 null(在 Console.log() 中检查),但它将 json 字符串 null 传递给 Controller ​​操作。 Controller 操作将对象视为字符串:

类(class):

 public int ID { get; set; }
 public string ProductName { get; set; }
 public int CategoryID { get; set; }
 public int BrandID { get; set; }
 public int Price1 { get; set; }
 public string Exchange { get; set; }
 public bool State { get; set; }

Controller :

  [HttpPost]
    public ActionResult AddProduct(string data)
    {
         //string data comes null here
    }

JQuery:

   var xy ={
             "data": { 
                 CategoryID: categoryID,
                 BrandID: brandID,
                 ProductName: productName,
                 Price1: price1,
                 ExchangeName: exchangeName,
                 State: state
             }
         };
         console.log(JSON.stringify(xy))

        $.ajax({
            url: "/Products/AddProduct/",
            type: 'POST',
             data: JSON.stringify(xy),          
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",         
            success: function (data) {

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText)

            }
        });

console.log 的输出(JSON.stringify(xy)):

 {"data":{"CategoryID":"63","BrandID":"1","ProductName":"pname","Price1":"199","State":"1"}}

我检查了很多答案,但无法找出我的问题。 感谢您的帮助。

最佳答案

在操作中您需要声明所有参数:

[HttpPost]
public ActionResult AddProduct(int CategoryID, int BrandID, string ProductName, double Price1, string ExchangeName, int State)
{
}

并传递这样的数据:

$.ajax({
            url: "/Products/AddProduct/",
            type: 'POST',
             data: {CategoryID: categoryID,
                 BrandID: brandID,
                 ProductName: productName,
                 Price1: price1,
                 ExchangeName: exchangeName,
                 State: state},          
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",         
            success: function (data) {

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText)

            }
        });

关于jquery - Ajax 向 Controller 操作发送空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44264869/

相关文章:

Jquery通过测试值获取单选按钮的id

jquery - 从发布的 JSON 获取经典 ASP 变量

php - 尝试使用php从mysql中选择记录,结果是没有标识符的json

java - JSONException : Value <br of type java. lang.String 无法转换为 JSONObject

javascript - $ 未定义 - 外部 js 文件中的 Ajax 调用

javascript - 使用ajax刷新页面的一部分 - 不起作用

python - 处理和保护 ajax 请求中的服务器功能..python

jquery - 使用 jQuery 在 iframe 中获取 HTML

javascript - (window).scrollTop() 滚动在 Mozilla 中出现错误?

android - 在 Android 中发送和解析 JSON 对象