1

I have to send a complex string via AJAX 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?

5 Answers 5

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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 }

Comments

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

Comments

0

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.