5

I would like to access a Model property value in ASP MVC at the View's javascript section

What is the best way to do so?

Thanks

2 Answers 2

16

I can't think of another way then just simpy printing it ;

<script type="text/javascript">
    var myJavaScripVar = '<%=Model.Property %>';
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

I'd also consider writing an extension method just to help clean things up a bit on your view, something that would look like <%=Html.JSVarFor(x=>x.Property, "myJavaScriptVar")%>
There's a potential security problem with this approach, if information shouldn't be publicly available. Client can see the infomration in the page source code. With ajax approach you can at least control the access to the data and e.g. detect web scraping.
1

Another option is to use an Ajax request to a controller method that returns a json result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.