Simplify writing JSON in a Razor view #2514
Description
A common task inside a razor view is converting part of the model into JSON and writing it to the page inside a script tag. The view model JSON can then be used by scripts executing on the page.
http://stackoverflow.com/questions/3365551/asp-net-mvc-how-to-convert-view-model-into-json-object (note: almost 70 thousand views)
There should be a simple way to use the application's configured JsonOutputFormatter to serialize JSON. With MVC5 in my own projects I use to add a HtmlHelper.Json(object)
extension method to simplify this task. It handled accessing the application's common JsonSerializerSettings and wrapping the string result in an HtmlString to avoid encoding issues.
Because JSON isn't HTML, I think it would be better to expose a Json
property on the base view, similar to the current Html
and Url
properties, with a class that exposes methods for serializing the model as JSON. A JsonHelper if you will. Alternatively, a simpler change would be to add a Json(object)
method to the base view for serializing JSON.
Having property or method immediately visible in intelli-sense will make this task simple and discoverable, and using JsonOutputFormatter underneath will mean any configured settings, e.g. camel case properties or date format, will automatically flow through to JSON serialized on the view.