ASP.NET MVC自动从AJAX解码JSON编码的参数 [英] ASP.NET MVC automatically decoding JSON-encoded parameters from AJAX

查看:174
本文介绍了ASP.NET MVC自动从AJAX解码JSON编码的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的JavaScript代码使用AJAX调用ASP.NET MVC方法时,它将传递JSON中的值.例如:

When my JavaScript code uses AJAX to call an ASP.NET MVC method, it passes values in JSON. For example:

var request = new XMLHttpRequest();
request.open("GET", "http://www.awesome.com/DoSomething?param1=%22some%20string%22&param2=1234", true);  // parameter string created with JSON.stringify

var request = new XMLHttpRequest();
request.open("POST", "http://www.awesome.com/DoSomething", true);
// set some headers
request.send("param1=%22some%20string%22&param2=1234");  // parameter string created with JSON.stringify

在ASP.NET MVC方面,我有处理呼叫的方法:

On the ASP.NET MVC side, I have my method to handle the call:

public void DoSomething(string param1, string param2) {

最糟糕的是param1用引号引起来:

What sucks is param1 is surrounded with quotation marks:

"some string"

更糟糕的是param2是 string :

What sucks more is param2 is the string:

1234

当我真的想要将该值作为整数时.因此,我要做的第一件事是使用DataContractJsonSerializer对这两个小狗进行解码,以使我的字符串没有引号,而我的第二个字符串被转换为int.头一到两次还不错,但是每做一个AJAX动作就变老了.

when I really want the value as an integer. So, the first thing I have to do is use DataContractJsonSerializer to decode both these puppies so my string doesn't have quotation marks and my second string is converted to an int. It's not too bad the first one or two times, but gets old having to do for every single AJAX action.

理想情况下,具有如下签名会很棒:

Ideally, it'd be awesome to have a signature like:

public void DoSomething(string param1, int param2)

我可以直接进入并使用我的值,而不必担心JSON解码,就像非AJAX动作一样.

where I could just jump right in and use my values without worrying about JSON decoding, just like is done for non-AJAX actions.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

哦,发布后,我发现了可以满足我需求的代码.请参阅底部附近的"ObjectFilter"类:

Oh, after posting I found code that does what I'm looking for. See the "ObjectFilter" class near the bottom:

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆