This is the first post in a series about jQuery and ASP.NET MVC 2 in Visual Studio 2010.
If you’ve had web development experience with ASP.NET and JavaScript it is highly likely that you’ve heard of or are maybe even interested in the new partnership of these two technologies.
Getting started isn’t terribly difficult, so I’m not going to over-complicate this post. A couple of things to clear up, then we’ll jump to the meat.
What is the ASP.NET MVC Framework?
Model-View-Controller, abbreviated as MVC, is a design pattern (a concept) that helps us organize our code in such a way that we can keep clear separation between our data, our behaviours & business rules and our user interface. Those parts, respectively are referred to as the model, the controller and the view.
The MVC Framework for ASP.NET MVC gives us tools support, conventions and a base set of classes to enable use of this pattern, rather than the default Page-Controller pattern that is used in ASP.NET.
What is jQuery?
There is a reference to every element in an HTML document and JavaScript has access to them. With JavaScript, you can manipulate the DOM and write scripts to animate parts of your web page, make AJAX requests or perform validation.
Once you’ve written that code, you then need to keep a repository for it (you don’t want to write it again). When you want a new feature you might need to make breaking changes. You will have performance issues and browser compatibility problems, perhaps even platform-related issues.
jQuery is a library of JavaScript code where the kinds of things you want to do are already done. It is cross-browser compatible, has many pre-built components and has better performance with every release.
Think of jQuery as a way of “doing something” to “a group of things,” even if it is a group of one. You almost always begin by finding “the things” and then performing an action on them. “The things” are elements of the DOM like links, DIV tags, images, form elements, forms or the document root itself.
The Basic Steps
For you impatient types out there (like me):
- Create an ASP.NET MVC 2 Web Application
- Add the jQuery reference to the Site.Master to enable jQuery on all pages
- Use the if(false) technique to enable IntelliSense on partial views
- Use script references to enable IntelliSense on stand-alone JavaScript files
The Meaty Version
Start Visual Studio 2010 and create a new project. Navigate to the Web category and select ASP.NET MVC 2 Web Application. Name your project (I used Spike.jQueryMvc) and press OK.
Visual Studio will ask you to create a Unit Test Project. Just say no for now (I’ll cover tests in a later post). Finish the wizard and you’ll have your MVC project created.
Open up the Site.Master file which you will find in Views –> Shared in the Solution Explorer. Expand the Scripts folder as well so that you can see the default scripts.
In the HEAD tag of your Site.Master, drag the jQuery ‘min’ file and, below it, the jQuery ‘vsdoc’ file. Wrap your vsdoc file with an if(false) statement. The vsdoc will never be written to the browser (because false is never true) but Visual Studio will pick up the file and enable IntelliSense with this trick.
We’re all set to use jQuery and Visual Studio 2010’s awesome IntelliSense.
Now, navigate to the Index.aspx page in Views –> Home and open it up. After the closing P tag, add the following code:
<script language="javascript" type="text/javascript">
$(function () {
$("p").click(function () {
$(this).slideUp();
});
})
</script>
You’ll notice as you’re typing that Visual Studio is popping up help text for your jQuery functions.
Press F5 to run the app. You will be prompted to modify the Web.Config file; accept this.
The browser will open and you’ll be staring at a slightly-modified default MVC page. Click on the text “To learn more about ASP.NET MVC” and see your jQuery in action.
FTW? How did that work?
Here’s the basics:
- A SCRIPT tag was added to the document
- We used a jQuery shortcut to wait for the document and run a function when it was completely loaded
- When loaded, we found all the P elements in the DOM and created an event handler to respond to user clicks. This is done with an anonymous function
- Inside our click event handler, we used another jQuery shortcut $(this) to select the P element that the user clicked on, and we told it to use the slideUp animation
The first shortcut is basically an event handler – in this case an anonymous function – that gets executed when the document is loaded. You should use this on every page because jQuery can’t find elements that haven’t yet been added to the DOM.
$(function () {
})
Inside this function – again, that gets executed after the DOM is loaded – we use a jQuery selector to find all the P elements in the document and attach a click handler to them.
$("p").click(...);
The selector can work with any element, ID or class. For IDs and classes you use the CSS-style sytax (# and . respectively), so for a input of type text with an ID of “first-name” you could find it with jQuery like so:
$("#first-name")
All that’s left is the anonymous function we used as an event handler.
function () {
$(this).slideUp();
}
We call the slideUp animation for the clicked element and let jQuery do it’s business.
Feedback
I have started this series to help a friend who is learning about web development. I found that by writing these tips out that I was gaining a better understanding of the underlaying technologies myself. I hope it can serve as a reference to others out there as well.
That said, if there’s something you’d like to point out, a question you have or a topic you’d like me to cover, please let me know and I will do my best to respond.
Thanks for the article. Waiting for the next ones...
ReplyDeleteHey Ramon,
ReplyDeleteNumber two and three are there, four should be up early this week. Glad you're finding them useful!
Cheers,
-jc
Superb article, best resource on getting started with jQuery in Asp.NET MVC I've found. Keep it up :)
ReplyDeleteDo you know how to use jquery inside a master page? I have tried to make the main menu of the default MVC2 project use jquery-ui tabs but trying to use jquery in the master page only results in object reference null exceptions.
ReplyDeleteMåns, this should work just fine. Make sure that your script block is near or at the end of BODY and that your menu elements are loaded before you try to manipulate them. Use something like $(function(){//put code here}); to ensure the document is loaded and put your code where the comment is. Finally, if you're loading the tabs via AJAX or similar, make sure you're doing the jQuery-ish stuff in the return call so that the elements are there. I'll see if I can rig up something similar (based on the default template). Cheers.
ReplyDeleteSorry...just want to clarify a couple things Måns.
ReplyDelete1) jQuery in a MasterPage works fine (I just checked it out).
2) After looking at the page template for the default site, you might want to think about a different approach (or give me a little more detail!). The Site.Master is used to drive content, so your content pages that would use the Site.Master are injected into that same master page. It would seem you're adding a layer that's not needed, no?
3) Further to point 2, the styles for the default template and the way the jQuery tabs are rendered might be a pain as-is. I think you'd be better off to scrap that Site.Master or tear it apart and start with fresh styles.
Cheers,
Thanks a lot. Very clear and well presented. I particularly like the while space and the scrolling that -- as a reader -- helped with digesting the text.
ReplyDeletei am a beginger, this is very useful