Accessing MVC's model property from Javascript

Null Reference picture Null Reference · May 3, 2013 · Viewed 309.6k times · Source

I have the following model which is wrapped in my view model

public class FloorPlanSettingsModel
{
    public int Id { get; set; }
    public int? MainFloorPlanId { get; set; }
    public string ImageDirectory { get; set; }
    public string ThumbnailDirectory { get; set; }
    public string IconsDirectory { get; set; }
}

How do I access one of the above properties from Javascript?

I tried this, but I got "undefined"

var floorplanSettings = "@Model.FloorPlanSettings";
alert(floorplanSettings.IconsDirectory);

Answer

Justin Helgerson picture Justin Helgerson · May 3, 2013

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));