Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"; alert(floorplanSettings.IconsDirectory); 
like image 289
Null Reference Avatar asked May 03 '13 14:05

Null Reference


People also ask

Can we use model in JavaScript?

How to access Model data in Javascript/Jquery code block in . cshtml file. There are two types of c# variable ( Model ) assignments to JavaScript variable.

What is a model in JavaScript?

Models are data structures that we use to define the shape of our data. You might also know them as objects, as in Object Oriented Programming, but in JavaScript everything is an Object, so it's not clear that we are talking about something specific if we just call them Objects.


1 Answers

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)); 
like image 128
Justin Helgerson Avatar answered Sep 23 '22 01:09

Justin Helgerson