2017-05-30 64 views
1

我想通过Asp.Net MVC中的Ajax提交页面输入。Ajax向控制器动作发送空参数

JQuery Ajax json数据不为null(在Console.log()中检查),但它将json字符串null传递给控制器​​操作。控制器动作方面的一个目的为字符串:

类别:

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

控制器:

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

JQuery的:的console.log的

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) 

      } 
     }); 

输出(JSON.stringify(XY )):

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

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

+0

console.log(JSON.stringify(xy));'?的输出是什么? – Sandman

+0

“AddProduct”方法中有哪些参数? '数据'或'CategoryID'等? –

+0

我更新了我的问题。 AddProduct方面的类参数作为字符串json数据来自ajax – Zeynep

回答

0

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

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

我还建议手动字符串化的数据是你不必要的额外工作。它将使更多的意义在你的C#代码来创建一个模型,然后让你的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... 
} 
+0

在您的答案我收到“无效的json原语:数据”间隔错误500 – Zeynep

1

需要声明的所有PARAMS:

[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) 

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

以这种方式传递您的数据