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);
How to access Model data in Javascript/Jquery code block in
.cshtml
fileThere are two types of c# variable (
Model
) assignments to JavaScript variable.int
,string
,DateTime
(ex:Model.Name
)Model
,Model.UserSettingsObj
)Lets look into the details of these two assignments.
For the rest of the answer lets consider the below
AppUser
Model as an example.And the values we assign this Model are
Property assignment
Lets use different syntax for assignment and observe the results.
1) Without wrapping property assignment in quotes.
As you can see there are couple of errors,
Raj
andTrue
is considered to be javascript variables and since they dont exist its anvariable undefined
error. Where as for the dateTime varialble the error isunexpected number
numbers cannot have special characters, The HTML tags are converted into its entity names so that the browser doesn't mix up your values and the HTML markup.2) Wrapping property assignment in Quotes.
The results are valid, So wrapping the property assignment in quotes gives us valid syntax. But note that the Number
Age
is now a string, So if you dont want that we can just remove the quotes and it will be rendered as a number type.3) Using
@Html.Raw
but without wrapping it in quotesThe results are similar to our test case 1. However using
@Html.Raw()
on theHTML
string did show us some change. The HTML is retained without changing to its entity names.From the docs Html.Raw()
But still we have errors in other lines.
4) Using
@Html.Raw
and also wrapping it within quotesThe results are good with all types. But our
HTML
data is now broken and this will break the scripts. The issue is because we are using single quotes'
to wrap the the data and even the data has single quotes.We can overcome this issue with 2 approaches.
1) use double quotes
" "
to wrap the HTML part. As the inner data has only single quotes. (Be sure that after wrapping with double quotes there are no"
within the data too)2) Escape the character meaning in your server side code. Like
Conclusion of property assignment
Html.Raw
to interpret your HTML data as is.Object assignment
Lets use different syntax for assignment and observe the results.
1) Without wrapping object assignment in quotes.
When you assign a c# object to javascript variable the value of the
.ToString()
of that oject will be assigned. Hence the above result.2 Wrapping object assignment in quotes
3) Using
Html.Raw
without quotes.4) Using
Html.Raw
along with quotesThe
Html.Raw
was of no much use for us while assigning a object to variable.5) Using
Json.Encode()
without quotesWe do see some change, We see our Model is being interpreted as a object. But we have those special characters changed into
entity names
. Also wrapping the above syntax in quotes is of no much use. We simply get the same result within quotes.From the docs of Json.Encode()
As you have already encountered this
entity Name
issue with property assignment and if you remember we overcame it with the use ofHtml.Raw
. So lets try that out. Lets combineHtml.Raw
andJson.Encode
6) Using
Html.Raw
andJson.Encode
without quotes.Result is a valid Javascript Object
7) Using
Html.Raw
andJson.Encode
within quotes.As you see wrapping with quotes gives us a JSON data
Conslusion on Object assignment
Html.Raw
andJson.Encode
in combintaion to assign your object to javascript variable as JavaScript object.Html.Raw
andJson.Encode
also wrap it withinquotes
to get a JSONNote: If you have observed the DataTime data format is not right. This is because as said earlier
Converts a data object to a string that is in the JavaScript Object Notation (JSON) format
and JSON does not contain adate
type. Other options to fix this is to add another line of code to handle this type alone using javascipt Date() objectHow to access Model data in Javascript/Jquery code block in
.js
fileRazor syntax has no meaning in
.js
file and hence we cannot directly use our Model insisde a.js
file. However there is a workaround.1) Solution is using javascript Global variables.
We have to assign the value to a global scoped javascipt variable and then use this variable within all code block of your
.cshtml
and.js
files. So the syntax would beWith this in place we can use the variables
userObj
anduserJsonObj
as and when needed.Note: I personally dont suggest using global variables as it gets very hard for maintainance. However if you have no other option then you can use it with having a proper naming convention .. something like
userAppDetails_global
.2) Using function() or
closure
Wrap all the code that is dependent on the model data in a function. And then execute this function from the.cshtml
file .external.js
.cshtml
fileNote: Your external file must be referenced prior to the above script. Else the
userDataDependent
function is undefined.Also note that the function must be in global scope too. So either solution we have to deal with global scoped players.
You could take your entire server-side model and turn it into a Javascript object by doing the following:
In your case if you just want the FloorPlanSettings object, simply pass the
Encode
method that property:Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:
Hope this helps...
try this: (you missed the single quotes)