ASP.NET MVC将JSON数据发送到Controller Action

时间:2021-05-17 16:35:34

I am trying to send some JSON data to my ASP.NET MVC3 controller action method, but it won't work no matter what I do.

我试图将一些JSON数据发送到我的ASP.NET MVC3控制器操作方法,但无论我做什么它都无法工作。

Here is my ajax call (it uses the JSON.stringify method from the json2.js):

这是我的ajax调用(它使用json2.js中的JSON.stringify方法):

$.ajax({
        url: '/Home/GetData',
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8;",
        data: JSON.stringify(filters_data),
        success: function (data) {
            alert(data);
        }
    });

The Fiddler shows the request like this:

Fiddler显示这样的请求:

POST http://localhost:51492/Home/GetData HTTP/1.1
Host: localhost:51492
Connection: keep-alive
Content-Length: 171
Origin: http://localhost:51492
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko)     Chrome/16.0.912.75 Safari/535.7
Content-Type: application/json; charset=UTF-8;
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:51492/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

{"Filters":[{"Field":3,"Operator":0,"Values":["30.01.2012.","30.01.2012."]},{"Field":2,"Operator":0,"Values":["-1"]},{"Field":0,"Operator":0,"Values":["some-string"]}]}

My c# code:

我的c#代码:

[HttpPost]
public string GetData(QueryFilters filters)
{
     return "Ho ho ho and a bottle of rum.";
}

[Serializable]
public enum Fields
{
        A,
        B,
        C,
        D
}

[Serializable]
public enum FilterOperator
{
    Is,
    Between,
    GreaterOrEqual,
}

[Serializable]
public class QueryFilter
{
    public Fields Field { get; set; }
    public FilterOperator Operator { get; set; }
    public List<string> Values { get; set; }
}

[Serializable]
public class QueryFilters
{
    public List<QueryFilter> Filters { get; set; }
}

I have added the following line to the Application_Start() method of global.asax.cs:

我已将以下行添加到global.asax.cs的Application_Start()方法中:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

The breakpoint in the action method 'GetData' is hit, but the value of the Filters property is null. Any ideas?

命中操作方法“GetData”中的断点,但Filters属性的值为null。有任何想法吗?

Another note: I have tried passing a much simpler object: Person - properties string Name and int Age, with the same result - it appears as if the automated model binding isn't working for me but I don't know how to check it.

另一个注意事项:我尝试传递一个更简单的对象:Person - 属性字符串Name和int Age,结果相同 - 看起来好像自动模型绑定对我不起作用但我不知道如何检查它。

1 个解决方案

#1


5  

The problem is that your action argument is called filters and that inside your QueryFilters model you have a property called Filters which confuses the default model binder.

问题是你的action参数被称为过滤器,而你的QueryFilters模型中有一个名为Filters的属性会混淆默认的模型绑定器。

So simply rename your action argument:

所以只需重命名你的动作参数:

[HttpPost]
public ActionResult GetData(QueryFilters model)
{
    return Json("Ho ho ho and a bottle of rum.");
}

Oh and notice that actions should return ActionResults not strings.

哦,请注意,操作应该返回ActionResults而不是字符串。

Also remove the following line from your global.asax:

同时从global.asax中删除以下行:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

ASP.NET MVC 3 already has this built-in.

ASP.NET MVC 3已经内置了这个。

Or if you absolutely for some reason need to have your action argument called filters then you could also modify the JSON request you are sending to this:

或者,如果您出于某种原因绝对需要将您的操作参数称为过滤器,那么您还可以修改要发送到此的JSON请求:

data: JSON.stringify({
    filters: { 
        Filters: [
            { "Field": 3, "Operator": 0, "Values": ["30.01.2012.", "30.01.2012."] },
            { "Field": 2, "Operator": 0, "Values": ["-1"] },
            { "Field": 0, "Operator": 0, "Values": ["some-string"] }
        ]
    }
}),

Now there's no more ambiguity.

现在不再有歧义了。

#1


5  

The problem is that your action argument is called filters and that inside your QueryFilters model you have a property called Filters which confuses the default model binder.

问题是你的action参数被称为过滤器,而你的QueryFilters模型中有一个名为Filters的属性会混淆默认的模型绑定器。

So simply rename your action argument:

所以只需重命名你的动作参数:

[HttpPost]
public ActionResult GetData(QueryFilters model)
{
    return Json("Ho ho ho and a bottle of rum.");
}

Oh and notice that actions should return ActionResults not strings.

哦,请注意,操作应该返回ActionResults而不是字符串。

Also remove the following line from your global.asax:

同时从global.asax中删除以下行:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

ASP.NET MVC 3 already has this built-in.

ASP.NET MVC 3已经内置了这个。

Or if you absolutely for some reason need to have your action argument called filters then you could also modify the JSON request you are sending to this:

或者,如果您出于某种原因绝对需要将您的操作参数称为过滤器,那么您还可以修改要发送到此的JSON请求:

data: JSON.stringify({
    filters: { 
        Filters: [
            { "Field": 3, "Operator": 0, "Values": ["30.01.2012.", "30.01.2012."] },
            { "Field": 2, "Operator": 0, "Values": ["-1"] },
            { "Field": 0, "Operator": 0, "Values": ["some-string"] }
        ]
    }
}),

Now there's no more ambiguity.

现在不再有歧义了。