Null Reference Null Reference - 1 year ago 166
Javascript Question

Accessing MVC's model property from Javascript

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";

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download