This is the first in a series of posts about things I found out while learning ASP.NET MVC. Today : adding jQuery support that will work wherever the app is deployed in a directory structure.
In order to reference the jQuery javascript files, I had to figure out how to add a realtive link to the .js files that would work even if the app was deployed to an unknown virtual directory. A quick question on StackOverflow.com led me to the following steps.
1) Create an extension method in the Helpers namespace…
public static string GetBasePath(this HtmlHelper helper) { var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); return urlHelper.Content("~/"); }
Next, point the link tags for my js file to the new location…
<script src="<%= Html.GetBasePath() %>Scripts/jquery-1.3.2.js" type="text/javascript"></script>
That’s it. All I had to do.
Of course, since I want to call data back from my MVC site via jQuery, I had to take a couple of extra steps to make the base path available to my scripts. Back in my master page, I created the following snippet.
<script language="javascript"> var rootUrl = "<%= Html.GetBasePath() %>"; </script>
Now I can call the data back from the site within my custom-defined jQuery script as follows…
$('#preview').click(function() { $.get(rootUrl + "jquery/getprovider/" + $(this).attr("name"), function(data) { $('#detailDiv').slideDown(300); $('#detailDiv').html(data); }); });
My #preview object has an id coded into its ‘name’ attribute so the jQuery controller can reference the correct data., eg.
<a href="#" name="12345">details</a>
One thought on “ASP.NET MVC – Preparing for the real world”
Comments are closed.