I have to get values from a controller method in a view to write into some javascript. In web pages it is as simple as <%=functionName()%>. Is there a way to do this in MVC. I cannot use the model because the javascript has to be available on page load. Any insights appreciated.
Share
Yes, of course.
Of course that you can use a view model, there’s nothing that would prevent you from doing so. So you start by defining it:
then have a controller action that will populate this view model and pass it the view:
and finally have a strongly typed view to this view model in which:
But now let’s suppose that you don’t want to pollute your view with javascript but have it in a separate js file instead (which of course is the correct way).
You could embed the value somewhere in your DOM, for example using HTML5
data-*attributes:and then in a separate javascript subscribe to the click event of this element and read the
data-*attribute in which we have JSON serialized the entire view model: