Software Developer, Technology Enthusiast, Husband and Dad based in Melbourne.

Encoding a ASP.NET MVC 4 Model for Javascript within a Razor Page

Sometimes you want to pass a property of a model to a Javascript variable, by encoding an ASP.NET 4 model into a Javascript variable, ?using ?HTML Helper and a strongly-typed model within a Razor Page. Razor Page

Razor Page

@model MyWebApp.Models.Foo
@{
ViewBag.Title = "Foo";
}

<script type="text/javascript">
var _model = @Html.Raw(Json.Encode(Model))
</script>
@Scripts.Render("/scripts/Foo.js")

 

  • The model must be strongly-typed.
  • Model encoding must be done at the top of the Razor page to allow the encoded JSON variable to be accessible.
  • JQuery must be included.

 

Example output

<script type="text/javascript">
var _model = {"Firstname":"Adam","Lastname":"Johnston"}
</script>

_model.Firstname
_model.Lastname