The prevailing practice for moving data between the controller and the view in ASP.NET MVC applications is to utilize a view model. While using a view model from within the view’s ASPX page is quite easy, utilizing it from JavaScript can be more complex. While JavaScript blocks declared inline on the view page can easily consume values from the model, external script files cannot. In order to take advantage of script batching and minimization, you should avoid the use of inline script blocks and instead use external JavaScript files (.js). What happens when you need to reference a value from the view model in your JavaScript though? Since the JavaScript files are not (by default) processed by the ASP.NET pipeline, it isn’t possible for them to leverage the Model; the Model exists server-side, while JavaScript is processed client-side.
I’ve struggled with this limitation since the first preview release of ASP.NET MVC. Here are a couple of the approaches that I tried (and hated):
Place scripts in partial views
Instead of following best-practices and placing JavaScript in an external script file, scripts can instead be placed in partial views. This simplifies the main view by encapsulating the script, and it does allow the script to be re-used. It also allows the script to easily reference values from the view model.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AwesomeViewModel>" %> <script type="text/javascript"> alert('Hello from the view model: <%=Model.Hello%>'); </script>
The downside to this approach is that the script cannot be easily minimized or combined, and it can’t be cached by the browser since it is actually rendered inline in the final markup produced by the view.
Pass view model properties through an initialization function
Another approach that I’ve used is to define an initialization function within my external JavaScript files. Any values that are needed by the script can be extracted from the model within the main view, then passed to the external JavaScript through the initialization function.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AwesomeViewModel>" %> ... <script type="text/javascript" src="ExternalScript.js"></script> <script type="text/javascript"> var name = "<%=Model.Name %>"; ExternalScript_Init(name); </script> ... //Contents of ExternalScript.js ExternalScript_Init(name) { alert("Hello from JavaScript: " + name); }
This approach is also less than ideal. Any values the script requires must be manually extracted from the view model, which makes maintenance more of a headache than it should be.
The ideal solution
The previous two approaches “work”, but they each have drawbacks. The ideal solution would allow the model to be easily consumed by external JavaScript files within a minimal amount of manual work. Adding a new property to the view model should require zero JavaScript in order to expose the new property for use by scripts. It turns out that this is actually quite easy to do….
The right way: serialize the model to JavaScript!
.NET 3.5 introduced the JavaScriptSerializer class for serializing objects to/from JSON. With it, most .NET types can be easily converted into a form that’s easily consumable by JavaScript. Scott Gu introduced a simple ToJSON extension method on his blog which can be used to transform a view model into JSON. When the output of this method is assigned to a JavaScript variable, the properties of the view model effectively become available to client-side script (note that methods defined on the view model, if any, are ignored by the JavaScriptSerializer).
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AwesomeViewModel>" %> ... <script type="text/javascript"> var Model = <%=Model.ToJson() %> //If needed, new properties can be added to the model, such as URLs for AJAX requests: Model.MyAjaxMethod = '<%=Html.BuildUrlFromExpression<MyController>(c => c.DoAjaxyThing()) %>'; </script>
The above code block should appear before any scripts that wish to access properties from the view model, which can reference view model properties easily:
<script type="text/javascript"> alert("Hello from the JSON view model:" + Model.Hello); </script>
This is a big improvement over the other two approaches I’ve tried (at least in my opinion), but it still requires me to perform this mundane serialization task on each view. An easy improvement is to move it to the master page:
<script type="text/javascript"> var Model = <%=Model != null ? Model.ToJson() : "{}" %>; </script>
Now every view that has a view model will automatically have a Model object available.
Thoughts? Suggestions? Anyone found a better solution that I’ve just overlooked somehow?
you develop your writing skills you will begin to seek out your voice and therefore the words will just flow naturally.
The book seems so interesting and content of the post is very valuable.Thanks for sharing this post.
Regards
Verduzco
Superb blog post. Bookmarked it already. Best regards, Olivia.
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
You had great positive ideas there. I did a search on the issue and found nearly all peoples will agree with your blog.
This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!
This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!
Hi there, I found your blog on Google while seeking for first aid for a heart attack and your post looks very interesting for me.
This is the best post on this topic i have ever read.
Nice post
Movie Buff?? Want to Watch Online movies, rent a DVD or a Blue ray and get it delivered at your doorstep. Missed out on a season of your favorite TV show, want to catch it up on DVD. This is the place to be.
I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.
I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the latest stuff you post.
I did a post about this very same topic a few days ago: http://jonathan-oliver.blogspot.com/2009/12/extreme-web-ui-scalability-part-2.html
In what we’re looking to do, we will have the ViewModel data *pre-serialized* out to JSON files rather than talking to a database. There are a critical number of things to be aware of when working with sensitive customer data in Javascript and how to avoid exposing that information to untrusted 3rd parties.
In any case, I plan to do a follow-up post regarding our findings on using the ViewModel data in Javascript and keeping it safe from cross-domain exploits.
I googled it on this subject and I believe some people would agree with your article. I need to bookmark this web site so I can comeback and read more posts. Keep up the good work.
I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
It appears that you have placed a lot of effort into your article and I require more of these on the net these days. I sincerely got a kick out of your post. I don’t really have much to say in response, I only wanted to comment to reply wonderful work.
This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!
This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.
I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the latest stuff you post.
I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks – you cleared up some things for me!
Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it’s nice to know that someone else also mentioned this as I had trouble finding the same info elsewhere. This was the first place that told me the answer. Thanks.
I am using java script in asp.net
excellent work.. will love to visit your blog in future..
useful information.. would like to visit your blog in future..
I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.
All major indexes gained less than 1 percent Tuesday, with the Standard & Poor’s 500 index and the Nasdaq composite index closing at new highs for the year.
I’ve really enjoyed reading your articles. More and more people are switching over to the idea of a raw food diet plan for a longer and healthier life. Even those people who don’t switch to 100% raw food diets find that by increasing the amount of raw fruits and vegetables in their diet they feel healthier and have an easier time maintaining a healthy body weight.
Great insights. I loved to read your article. You must be putting a lot of time into your blog!
software systems to choose from but, if you are just starting out in Sales, or if you own a small business..
@Jonathan,
I also thought about the possible security issues with exposing the model directly via JavaScript. However, the view model is actually already exposed (though not as concisely) through the HTML on the form. If you use the built-in model binding and HTML helpers, it is quite easy to discern the view model’s structure and data. In cases where a domain model or other object is being used that might contain sensitive data, I would not use this approach, but then again such an approach would not be best-practices in the first place.
This is a really good read for me. Must agree that you are one of the best bloggers I ever saw. Thanks for posting this informative article.
i have a blog and am really looking to alter around the theme, however am scared to death to mess with it for fear of the search engines punishing me. I am very new to all of this …so i am just not positive exactly how to try to to it all yet. I’ll just keep working on it one day at a time Smile Thanks for any help you can offer here.
Great blog. You must give it protection against spammer from ruining it.
With this approach, the entire model will be made available client side. James Newton-King has a recent post about some strategies to reduce the amount of unneeded properties being rendered here: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx
This is actually a Great knowledge gaining writing and all thanks to google search engine get me on here. I enjoyed reading your news and added to the bookmarks. The points you tried to put up was clearly understandable. My sister also appreciated after reading this writing. I will browse for more sooner. bye – Abbie
Hello, perhaps this posting is off topic but anyways, I’ve been browsing around your weblog and it looks really neat. It is obvious you know the topic and you seem passionate about it. I’m creating a fresh website and I am striving to make it look great, as well as provide the best website content. I’ve gleaned a good deal visiting your internet site and also I look forward to additional quality content and will be coming back soon. Thanks.
I am impressed by the way you handled this topic. It is not often I come across a blog with newsworthy articles like yours. I will bookmark your feed to stay up to date with your forthcoming updates. I like it and do preserve up the good work.
Easily, the article is actually the greatest on this notable topic. I harmonise with your conclusions and will eagerly look forward to your next updates. Saying thanks will not just be adequate, for the exceptional clarity in your writing. I will at once grab your rss feed to stay informed of any updates. Pleasant work and much success in your business enterprize!
this was a great movie. you should really watch it
Hi. I needed to drop you a quick note to impart my thanks. I’ve been following your blog for a month or so and have picked up a heap of solid information as well as enjoyed the way you’ve structured your site. I am attempting to run my own blog however I think its too general and I would like to focus more on smaller topics.
Considerably, the article is in reality the best on this laudable topic. I agree with your conclusions and will eagerly look forward to your approaching updates. Just saying thanks will not just be enough, for the extraordinary clarity in your writing. I will directly grab your rss feed to stay abreast of any updates. Admirable work and much success in your business efforts!
Thanks
Can’t seem to find the RSS feed for your site. Knowing me it’s probably sitting right in front of my face, LOL.
Hi I found your site by mistake when i was searching yahoo for this registry cleaner issue, I must say your site is really helpful I also love the design, its amazing!. I dont have that much time to read all your post at the moment but I have bookmarked your site and also add your RSS feeds. I will be back in a day or two. thanks for a great site.
Awesome article. Bookmarked.
This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article!
This is informative information and great to grasp you talk about a good subject.
Hey very unique blog there, just wondering what anti-spam plugin you use for comments section because i get a lot on my blog! 🙁 Wish if I could found them..
This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article
hey i decided to comment and telll you hott layout and nice site! great job with the blog!!! x-)
I did a search on this subject and I guess many people would agree with your blog. I need to bookmark this web site so I can comeback and read more posts. Keep up the good work.
hey, your post truly aids, now i receive the same troubles, and i have no idea on what are the best registry cleaner. luckily i look bing and found your post, it helps me get rid of my trouble.
thanks againone thing, can i paste your entry on my blog? i will add the source.regards!
i stumble across your blog searching for a blog platform for asp. i think BlogEngine is one of the best blogs around.. thanks for this nice article…
Great read. A+++++++
hey, your post really assists, now i receive the same problems, and i have no idea on what are the best registry cleaner. thankgod i research yahoo and discovered your post, it helps me get rid of my trouble.
thanks once againjust one thing, can i paste your article on my site? i will add the source and credit to your site.regards!
Solid article. I just emailed this to my friend and subscribed to your feed as well, job well done!
What’s up, I just found your blog – thanks for writing. As an FYI that it’s not showing up correctly on the BlackBerry Browser (I have a Storm). Either way, I’m now subscribed to the RSS feed on my PC, so thanks again!
Intimately, the post is really the greatest on this noteworthy topic. I agree with your conclusions and will thirstily look forward to your next updates. Just saying thanks will not just be enough, for the fantasti c lucidity in your writing. I will immediately grab your rss feed to stay abreast of any updates. Fabulous work and much success in your business dealings!
This is nice information and good to know you write about a good subjectpost.
You are right, people should listen to what you are saying because are absolutely right. 😀
Advantageously, the article is in reality the greatest on this deserving topic. I agree with your conclusions and will eagerly look forward to your forthcoming updates. Just saying thanks will not just be enough, for the fantasti c clarity in your writing. I will instantly grab your rss feed to stay informed of any updates. Good work and much success in your business endeavors!
Hey really nice website, I saw your web site when I was doing investigation on some methods to enhance my blog. I was just which spam software you employ for comments as I get a great deal on my site.
Where do you get this information? Thanks
I found your web page from aol and it is amazing. Thnx for providing such an amazing post!!
Interesting read. There is currently quite a lot of information around this subject around and about on the net and some are most defintely better than others. You have caught the detail here just right which makes for a refreshing change – thanks.
I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post.
This was novel. I wished I could read every post, but i have to go back to work now… But I’ll return.
Hi I reach this site by mistake when i was searching bing for this registry cleaner issue, I have to say your site is really helpful I also love the theme, its amazing!. I dont have that much time to read all your post at the moment but I have bookmarked your site and also signed up for your RSS feeds. I will be back in a day or two. thanks for a great site.