Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url Encode javascript object literal

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?

like image 682
JayAr Avatar asked Jun 15 '12 15:06

JayAr


1 Answers

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
like image 114
zzzzBov Avatar answered Sep 27 '22 20:09

zzzzBov