do you write your JavaScript in a ASP.NET MVC view … or in a separate JavaScript file?

I follow a handful of rules:

  1. Don’t attach a variable directly to the DOM unless absolutely necessary.
  2. Place as much information in js files as possible. The fewer js files, the better.
  3. Version your js files. When publishing, minify and mash via Chirpy or SquishIt
  4. In js, minimize your dependency on dynamic server-side values (generated ids, etc.) when you can.

So, here’s an example:

I’ll add jQuery and jQuery metadata to my project:
http://plugins.jquery.com/project/metadata

Then, in my master js file, I’ll extend jQuery with my own namespace:

$.extend({
   fatDish : {
     url : {},
     urls : function(a) {
        $.extend($.fatDish.url, a);
     }
   }
});

Almost all of my customized js logic will live in the $.fatDish namespace.

Now, let’s say I want to pass a MVC route to $.fatDish. In my aspx page, I’d write the following:

<script src="https://stackoverflow.com/questions/4624626/@Url.Content("~/path/master.js")" type="text/javascript"></script>
<script type="text/javascript">
   $.fatDish.urls({
      path1 : '@Url.Action("Index", "Home")'
   });
</script>

In a js file, I can now write:

window.location = $.fatDish.url.path1;

A second approach is to use jQuery metadata (which I mentioned above). On your aspx page, you could write something like:

<div class="faux-link {act:'@Url.Action("Index", "Home")'}">Go Somewhere</div>

Then, in your js file, you can grab the route value like so:

$('.faux-link').click(function() {
   var $this = $(this);
   var href = $this.metadata().act;
   window.location = href;
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)