开发者

How to send complex string via AJAX

I have to send a complex string via AJA开发者_如何学GoX in ASP.NET MVC from my view to a particular controller action.

The string needs to contain all sorts of characters like < , > , & , " , ' .

I am using the following code in javascript :


var request = new Sys.Net.WebRequest();
request.set_url("/Controller/Action?Param=" + str) ; // str is the string to be sent
request.set_httpVerb("POST");
request.invoke();

But when I run the page, the AJAX request does not reach the action in the controller.

Can anyone tell how to achieve this?


use encodeURIComponent on str

var request = new Sys.Net.WebRequest();
request.set_url("/Controller/Action?Param=" + encodeURIComponent(str)) ; // str is the string to be sent
request.set_httpVerb("POST");
request.invoke();


I think you're looking for Server.UrlEncode. or just plain encodeURI/encodeURIComponent in javascript.

Encode the raw data before appending it to the URL.


create your delete method in global.asax like this

routes.MapRoute("Delete", //Route name
                "ControllerName/MethodName/{id}",
                new { controller = "controller Name", action = "Method Name", id = 1 }


request.set_url("/Controller/Action?Param='" + str+"'"+) ;


I would recommend you jQuery. Microsoft AJAX is like stone age and totally deprecated in ASP.NET MVC. I mean if you was working on some legacy ASP.NET WebForms application you would have had an excuse but in ASP.NET MVC there is no excuse. So:

$.ajax({
    url: '<%= Url.Action("Action", "Controller")',
    type: 'POST',
    data: { Param: str },
    success: function(result) {
        // handle the success
    }
});

Also if you need to send special characters such as <, >, ... you must ensure that the corresponding controller action is decorated with the [ValidateInput(false)] attribute:

[ValidateInput(false)]
public ActionResult Action(string Param)
{
    ...
}

and if you are using ASP.NET 4.0 you might also need to set the following in your web.config for this to work:

<httpRuntime requestValidationMode="2.0" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜