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 "
?
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).
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.
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.
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()
.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With