将 json 发送到控制器时,ASP.NET mvc 4 控制器参数始终为空,为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20384242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:06:25  来源:igfitidea点击:

ASP.NET mvc 4 controller parameter always null when sending json to controller, why?

asp.net-mvcjsonobjectcontroller

提问by Ga?per Sladi?

There are some similar posts already here, and tried every solution suggested, and still does not work... I can not get value inside controller, it is always null. Below is the code. Am I missing something?

这里已经有一些类似的帖子,并尝试了所有建议的解决方案,但仍然不起作用......我无法在控制器中获取值,它始终为空。下面是代码。我错过了什么吗?

Client side javascript

客户端javascript

   function getChart() {
       JSONString3 = { HAxis : [{ Name : "monday" }] };
       jQuery.ajaxSettings.traditional = true;
        $.ajax({
            url: "@Url.Action("getChart","SBM")",
            type: 'POST',
            contentType: 'json',
            dataType: 'html',
            data: JSONString3,
            success: function (data) {
                var imagestring = btoa(data);
                $('#ChartImage').attr('src', "data:image/png;base64," + imagestring + "?" + new       Date().getTime());
            }
        })
        jQuery.ajaxSettings.traditional = false;
    }

MVC Controller

MVC控制器

    [Authorize]
    [HttpPost]
    public ActionResult getChart(YAxis HAxis)
    {
        YAxis XAxisvalue = HAxis;
        Charts chart = new Charts();
        MemoryStream ms = new MemoryStream();
        chart.Chart.SaveImage(ms);
        string image = Convert.ToBase64String(ms.GetBuffer());
        return File(ms.GetBuffer(), "image/png", "Chart.png");
    }

Model

模型

public class YAxis
{
    public string Name { get; set; }
}

回答by Ga?per Sladi?

Thank you guys for the directions and solutions. The solution is a combination of all of your suggestions, so I decided to round it up in one post.

谢谢各位大侠的指点和解决方法。解决方案是您所有建议的组合,因此我决定将其汇总在一篇文章中。

Solution to the problem is as follows:

问题的解决方法如下:

  1. contentTypeshould be application/json(as Ant P suggested above)
  2. json data should be in form of JSONString3 = {"Name" : "monday" }(as Ant P suggested above)
  3. before sending to controller, json should be stringifyedas follows: JSONString3 = JSON.stringify(JSONString3)(as Quan suggested)
  1. contentType应该是application/json(如上面建议的Ant P)
  2. json 数据的形式应为JSONString3 = {"Name" : "monday" }(如上面建议的 Ant P)
  3. 在发送到控制器之前,json 应该stringifyed如下:(JSONString3 = JSON.stringify(JSONString3)如 Quan 建议)

Client side javascript

客户端javascript

function getChart() {
               JSONString3 = { "Name" : "monday" };
               jQuery.ajaxSettings.traditional = true;
                $.ajax({
                    url: "@Url.Action("getChart","SBM")",
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'html',
                    data: JSON.stringify(JSONString3),
                    success: function (data) {
                        var imagestring = btoa(data);
                        $('#ChartImage').attr('src', "data:image/png;base64," + imagestring + "?" + new       Date().getTime());
                    }
                })
                jQuery.ajaxSettings.traditional = false;
    }

MVC Controller

MVC控制器

[Authorize]
[HttpPost]
public ActionResult getChart(YAxis HAxis)
{
    YAxis XAxisvalue = HAxis;
    Charts chart = new Charts();
    MemoryStream ms = new MemoryStream();
    chart.Chart.SaveImage(ms);
    string image = Convert.ToBase64String(ms.GetBuffer());
    return File(ms.GetBuffer(), "image/png", "Chart.png");
}

Model

模型

public class YAxis
{
    public string Name { get; set; }
}

Instead of this:

取而代之的是:

JSONString3 = { "Name" : "monday" };

we can do this:

我们可以完成这个:

var JSONString3 = {};
JSONString.Name = "monday";

But we still need to stringify object before posting to controller!!!

但是我们仍然需要在发布到控制器之前对对象进行字符串化!!!

To pass multiple objects to controller, below is the example

将多个对象传递给控制器​​,下面是示例

Client side javascript

客户端javascript

   function getChart() {

        //first json object
        //note: each object Property name must be the same as it is in the Models classes on    server side
        Category = {};
        Category.Name = "Category1";
        Category.Values = [];
        Category.Values[0] = "CategoryValue1";
        Category.Values[1] = "CategoryValue2";

        //second json object
        XAxis = {};
        XAxis.Name = "XAxis1";
        XAxis.Values = [];
        XAxis.Values[0] = "XAxisValue1";
        XAxis.Values[1] = "XAxisValue2";

        //third json object
        YAxis = {};
        YAxis.Name = "YAxis1";

        //convert all three objects to string
        //note: each object name should be the same as the controller parameter is!!
        var StringToPost = JSON.stringify({CategoryObject : Category, XAxisObject : XAxis, YAxisObject : YAxis});

        $.ajax({
            url: "@Url.Action("getChart","SBM")",
            type: 'POST',
            contentType: "application/json",
            dataType: 'html',
            data: StringToPost,
            success: function (data) {
                var imagestring = btoa(data);
                $('#ChartImage').html(data);
            }
        })
    }

MVC Controller

MVC控制器

[HttpPost]
public ActionResult getChart(Category CategoryObject, XAxis XAxisObject, YAxis YAxisObject)
{
    //do some stuff with objects here and return something to client
    return PartialView("_Chart");
}

Category model

品类模型

public class Category
{
    public string Name { get; set; }
    public List<string> Values { get; set; }
}

XAxis model

X轴模型

public class XAxis
{
    public string Name { get; set; }
    public List<string> Values { get; set; }
}

YAxis model

Y轴型号

public class YAxis
{
    public string Name { get; set; }
}

Hope it will help someone to clarify the whole picture!

希望它会帮助有人澄清整个画面!

回答by live-love

I had same problem (parameter always null), but my solution was different.

我有同样的问题(参数始终为空),但我的解决方案不同。

Make sure that your ActionResult method parameter doesn't have the same name as the JSON object property.

确保您的 ActionResult 方法参数与 JSON 对象属性的名称不同。

In this example I renamed myParam to myNewParam to differentiate from MyParam property.

在本例中,我将 myParam 重命名为 myNewParam 以区别于 MyParam 属性。

Example: This won't work:

示例:这行不通:

    var myObj = {
        ID: '0',
        MyParam: $('#mycontrol').val(),
    }; 

    $.ajax({
        type: "POST",
        url: '@Url.Action("MyAction", "MyModel")',
        cache: false,
        data: JSON.stringify(myObj),
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
        }
    })

[HttpPost]
        public ActionResult MyAction(Class1 myParam)

This will work:

这将起作用:

    var myObj = {
        ID: '0',
        MyParam: $('#mycontrol').val(),
    }; 

    $.ajax({
        type: "POST",
        url: '@Url.Action("MyAction", "MyModel")',
        cache: false,
        data: JSON.stringify(myObj),
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
        }
    })

[HttpPost]
        public ActionResult MyAction(Class1 myNewParam) -->renamed

回答by Ant P

Looks to me like you're trying to pass an array of objects:

在我看来,您正在尝试传递一组对象:

JSONString3 = { HAxis : [{ Name : "monday" }] };

When your action only wants one:

当您的操作只需要一个时:

public ActionResult getChart(YAxis HAxis)

Maybe you only meant to pass one?

也许你只是想通过一个?

JSONString3 = { "Name": "monday" };

回答by Quan Truong

JSONString3 = { "Name": "monday" };

You should post it to controller as a string, so use JSON.stringify to convert, i dont know how to use your ajax type, i just know to use $.post... T_T

你应该把它作为字符串发布到控制器,所以使用 JSON.stringify 进行转换,我不知道如何使用你的 ajax 类型,我只知道使用 $.post... T_T

 $.post('@Url.Action("getChart","SBM")', {yourJson : data:JSON.stringify(JSONString3)} , function(data) {
            if (data.success) {
var imagestring = btoa(data.name);
                $('#ChartImage').attr('src', "data:image/png;base64," + imagestring + "?" + new       Date().getTime());
   }
});

In controller,

在控制器中,

    public ActionResult getChart(string yourJson)
        {
         YAxis  yAxis= JsonConvert.DeserializeObject<YAxis>(yourValue);
          //  ....... your code here
          return Json(new{success=true,name=yAxis.Name},JsonRequestBehavior.AllowGet);
        }

** Note : JsonConvert is method of using Newtonsoft.Json; , please add Newtonsoft reference.

** 注意:JsonConvert 是使用 Newtonsoft.Json 的方法;,请添加 Newtonsoft 参考。

回答by user3307830

Adding a datatype attribute to the controller method solved it for me.

向控制器方法添加数据类型属性为我解决了这个问题。

[JsonFilter(Param="yourParamName", JsonDataType=typeof(YourParamType))]
[HttpPost]
public ActionResult yourFunction(YourParamType YourParamName)
{
    //do some stuff
}