Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Object to JSON in MVC 4

I am converting an object to JSON using JavaScriptSerializer and I can see this JSON output in server code:

[{"UserId":1,"UserName":"Admin"}]

But in the UI it's getting converted to something like below

[{"UserId":1,"UserName":"Admin"}].

How to escape those "?

like image 737
user1735105 Avatar asked Oct 10 '12 13:10

user1735105


People also ask

Can Actionresult return JSON?

JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

How pass JSON object in post request in MVC?

Make sure you specify POST type, as ajax method uses GET method by default. MVC Controller: Decorate the Action method with HttpPost verb. This action method will only handle http post request from browser. Ajax submission from the browser will be automatically deserialized to FormData c# class as a poco.

What is JSON in MVC with example?

JSON Java Script Object Notation is a very familiar and commonly used concept. It is a data interchange medium and is very lightweight. It is one kind of syntax for storing and passing data. Since it is Javascript object notation, it uses the javascript style of syntax, but actually is text only.


2 Answers

If you are using the Razor view engine you need to use the Html.Raw method:

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

Notice the usage of the Json.Encode method which is shorter and equivalent to new JavaScriptSerializer().Serialize().

like image 81
Darin Dimitrov Avatar answered Oct 08 '22 15:10

Darin Dimitrov


Why are you doing that? Why not just return a JsonResult?

public ActionResult MyMethod()
{
    List<ListItem> list = new List<ListItem>() {
        new ListItem() { UserId = "1", UserName = "Admin" },
        new ListItem() { UserId = "2", UserName = "JohnDoe" },
        new ListItem() { UserId = "3", UserName = "JaneDoe" }};

    return this.Json(list);
}
like image 22
Erik Funkenbusch Avatar answered Oct 08 '22 14:10

Erik Funkenbusch