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?

1

2 Answers 2

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

1 Comment

Exactly what I needed, thank you, but I need to check further because the model contains a list actually...
-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.

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.