Search code examples
c#.netasp.net-mvcasp.net-mvc-4form-post

Posting string value with "+" to action replaces value with space


I've done a HTTP POST to an action with the form value:

name=123+456

But in my action it comes through as:

123 456

So the model binder replaces "+" with a space.

[HttpPost]
public JsonResult MyAction(string name)
{

Any ideas? Do i have to create a custom model binder or something?

EDIT:

This is posted in jquery as follows:

$.ajax({
...
data: "name=" + $('#signin-username').val()
...
});

Should i use JSON.stringify or something similar? Or do i have to manually encode?


Solution

  • The + character is how spaces are usually encoded in URL's. Try encoding the +:

    name=123%2B456
    

    In your jQuery, use the encodeURIComponent method:

    $.ajax({
        ...
        data: "name=" + encodeURIComponent($('#signin-username').val())
        ...
    });