Friday, June 8, 2012

ASP.NET MVC: How to get model values from separate javascript file


Problem
How to get ASP.NET MVC model values from separate javascript file?

Solution
There are many ways to get model values from separate javascript file. Here are a couple of way to do it:

1. If you are using HTML5 you can use custom data attributes
 <div id="baseTargetUrl" data-basetargeturl="<%= Url.Content("~/") %>" />  
and get custom attribute value from javascript file
 var rootUrl = location.protocol + '//' + location.host +  
 $('#baseTargetUrl').data('basetargeturl');  
2. Set javascript variable from view
 <script type="text/javascript">  
 var baseTargetUrl= <%= Url.Content("~/") %>;  
 </script>  
and use this variable from separate javascript file

3. Extend jQuery to allow own namespace to store values. Here is a great example how to do it