13

I have Model

public class SomeModel
{
    public string SomeText { get; set; }
}

In javascript I make an javascript object literal of the model:

var model = {
                SomeText: "test"
            };
var serializedData = JSON.stringify(model);

This makes a string which looks like the following:

"{"SomeText":"test"}"

Now suppose I want to send this model to a controller which accepts a model like this with the following function:

public void Index(SomeModel model)
{
}

What I need is an url string in which the model has the following form:

"?SomeText=test"

I know that ajax does exactly this when you send the model via ajax post:

$.ajax({type:"POST", 
        url: "someUrl", 
        data: serializedData,
        ...
});

The 'data:' url-encodes the serialized data.

But I actually do not want to use ajax, so I need to build this url myself. I want to do exactly the same thing as ajax does with 'data:'. How can I url-encode the serialized data myself?

JayAr
  • 441
  • 1
  • 5
  • 19

2 Answers2

34

You should use jQuery.param:

$.param({foo:'bar', fizz:'buzz'});
//produces foo=bar&fizz=buzz

Arrays are ok too:

$.param({foo:['bar', 'baz']});
//produces foo%5B%5D=bar&foo%5B%5D=baz
//which is the url encoded form of: foo[]=bar&foo[]=baz

if you need the traditional array syntax, use the second parameter:

$.param({foo:['bar','baz']}, true);
//produces foo=bar&foo=baz
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Exactly what I needed, thank you, but I need to check further because the model contains a list actually... – JayAr Jun 15 '12 at 16:09
-2

To escape a single value, Javascript has the function escape. You must provide your own function to iterate through the object, add the keys, and so on.

EDIT

Esailija is kind enough to remind me that escape does not handle many common cases properly, and encodeURIComponent is much better. If you're already using jQuery (and you should be), zzzzBov's answer is better still.

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144