Ajax将null参数发送到控制器操作

时间:2017-05-30 14:21:21

标签: jquery json ajax asp.net-mvc

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

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

类别:

-in

控制器:

 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; }

JQuery的:

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

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

   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)

            }
        });

我检查了很多答案,但无法弄清楚我的问题。 谢谢你的帮助。

3 个答案:

答案 0 :(得分: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)

            }
        });

答案 1 :(得分:0)

您需要提供您发送数据的密钥的名称。试试这个:

data: { data: JSON.stringify(xy.data) },       

我还建议手动对数据进行字符串化是不必要的额外工作。在C#代码中创建一个Model然后让ModelBinder为你工作更有意义:

data: xy.data,
// model definition:
public class Product {
  public int CategoryID { get; set; }
  public int BrandID { get; set; }
  public string ProductName { get; set; }
  public decimal Price1 { get; set; }
  public string ExchangeName { get; set; }
  public string State { get; set; }
}

// in your controller:
[HttpPost]
public ActionResult AddProduct(Product product)
{
  // work with the hydrated Product class here...
}

答案 2 :(得分:0)

 data: new{data = JSON.stringify(xy)}

以这种方式传递您的数据