我的视图中有一个json结果,我需要将它发送回控制器,将其转换为.CSV文件,但是我在控制器中得到null甚至认为它包含数据,这里是我的视图&#34 ;导致"包含数据但在我的控制器中我得到它null,任何帮助都将受到高度赞赏
$.ajax({
dataType: "json",
type: "POST",
url: "@Url.Action("CreateCSVFile", "Turbine")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "result": result }),
success: function (result) {
}
})
这是我的控制器,我得到NULL:
public void CreateCSVFile(string result)
{
//XmlNode xml = JSON JSON.DeserializeXmlNode("{records:{record:" + json + "}}");
DataTable dt = JsonConvert.DeserializeObject<DataTable>(result);
string strFilePath = @"C:\myCSVfile.csv";
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
//First we will write the headers.
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
答案 0 :(得分:0)
这段代码对我有用。我甚至不在我的ajax请求中包含数据类型和contenttype。
$.ajax({
url: "Controller/MethodName",
type: 'POST',
data: { "bId": id, "status": stat },
success: function (data) {
}
});
[HttpPost]
public JsonResult CreateCSVFile(string bId, bool status)
{
return Json(someReturn);
}
希望这会对你有所帮助。祝你好运!