-2

Is there any simple way to convert an C#-object into a plain string that is escaped and can be used by javascript?

I try to pass the string into a jQuery-function which will replace some parts of this string with real values to pass them as request-object via $.ajax.

Whatever I tried (found in the internet) doesn't work.

Currently I have:

var jsVariable = "@Html.Raw(Json.Encode(new MyClass()))"

but this throws an Uncaught SyntaxError: Unexpected identifier as of the " are not escaped correctly.

Update 1

At the end I would like to have the JSON-string like

"{"Prop1": "{0}", "Prop2":"{1}"}"

on which I can (in javascript) call

var request = string.Format(jsVariable, value1, value2);

to enable

$.ajax({
    type: "POST",
    url: "someUrl",
    data: $.parseJson(request),
    success: function(data) {
        console.log("success");
    },
    dataType: "JSON"
})
3
  • 1
    are you looking for : newtonsoft.com/json ? Commented Sep 7, 2015 at 12:49
  • I think you can use the json serializeation method that will convert to the json object Commented Sep 7, 2015 at 12:49
  • @tschmit007 : same want to say Commented Sep 7, 2015 at 12:50

1 Answer 1

1

Just get rid of the double quotes.

Make sure this is added in the script tag of your view.

var jsVariable = @Html.Raw(Json.Encode(new MyClass()))

you'd then get a javascript object with its properties - provided MyClass is defined, and is accessible in your CSHTML.

jsVariable.myProp, jsVariable.myOtherProp . . etc

Sign up to request clarification or add additional context in comments.

2 Comments

That's what I partially also ended up with. I thought there would be a simple way to have this as string inside javascript to replace the property-values like string.Format(jsVariable, value1, value2) and build the $.ajax data from this. So it's more like some kind of a template of the Request-object
if you want to alter the property values and pass it to your ajax call - you could just alter your properties like this: jsVariable.myProp = yourNewValue, then you could pass the same object to your ajax call - data: JSON.stringify(jsVariable)

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.