In our last episode we went over the basics of JavaScript and the jQuery library. In this installment I will show you the basics of MVC and how it renders HTML differently than Web Forms pages, and finish up showing some basic Ajax with jQuery.

When ASP.NET first arrived it was a good thing. Web Forms allowed developers to build websites in a way that was very similar to how Windows Forms applications where built, with drag and drop of controls and a "code behind" architecture. Web Forms served their purpose for many, many applications in the enterprise, and many commercial applications, both large and small were successfully built using this technology.

When "Web 2.0" arrived, complete with Ajaxy interactions, Microsoft put forth their own brand of controls to handle this, and for the most part this worked, and continues to work well. However the Web Forms framework makes it difficult to build clean, lean web sites, as the technology depends on many different things in the rendered HTML to make it usable when posting back to the server. Two of the main items are ViewState and Control Rendering.

ViewState is sent to the browser as a way to capture what is on the page, and what has been changed when the request is sent back to the browser. For ViewState to work, controls on the page need to be rendered with specifically named ID's. This makes it difficult to use JavaScript to find elements on the page by their ID. For example adding a button to a page that is using an ASP.NET Master Page will render the following HTML:

Source code:

1: <asp:Panel ID="Panel1" runat="server">

2: <asp:Button ID="btnClick" runat="server" Text="Button" />

3: </asp:Panel>

Rendered HTML:

1:

2: <input type="submit" name="ctl00$MainContent$btnClick"

3: value="Button" id="MainContent_btnClick" />

4:

ViewState:

1:

2: <input type="hidden" name="VIEWSTATE" id="VIEWSTATE"

3: value="/wEPDwUJNjE3ODYxMzIwZGQjyMGaAJ/BFAzxJv1b /lEXPaj4I/hCsdqNKZUozZiyw==" />

4:

If you notice you will see both the name and the id of the button has been changed to show that it is a child of the asp:Panel which is a child of the ASP.NET MasterPage. The ViewState in this example is fairly lean, but in large pages, it can become very large, and this is data the browser needs to download.

While this is all fine and dandy, trying to access these elements can be difficult, especially when trying to use jQuery's selector mechanisims. You may think, that if you keep the name the same when traversing the DOM, will keep it good. But if for some reason the ID of the parent element changes in your code, then the names will change. There are some tricks you can use, but they are not the basis of this tutorial.

Now, let's look at the same page when rendered with MVC:

Source code:

1: <asp:Panel ID="Panel1" runat="server">

2:

3: </asp:Panel>

Rendered HTML:

1:

2:

3:

Now keep in mind that ASP.NET MVC does not typically use ASP.NET controls and in this example I am using a standard HTML input tag for the submit button.

The ASP.NET MVC Framework - What is it?

Now before we get into a big discussion about what is better and what is not, and all the underpinnings of "who moved my cheese", MVC is yet another way to build web sites using the .NET Framework. It is a web application framework which implements the model-view-controller pattern of development. It is based on ASP.NET and allows the development of a web application to be built using three roles; Models - the data coming into and out the application, Views - the displayed pages, and Controllers - which handle the traffic coming in for HttpRequest and HttpResponse.

Microsoft released a CTP version of MVC in December, 2007, MVC version 1 in March 2009 and MVC version 2 in March 2010. They are currently working on version 3.

The default View engine for MVC is the Web Forms view engine and this view engine uses regular .aspx pages to design the layout of the user interaction pieces of the web site or web application. Instead of PostBacks any interactions are routed to the Controllers using a Routing mechanism.

A typical ASP.NET MVC application will have the following directory structure as seen in this figure:

MVC-Folder-Structure

As you can see there are folders for Controllers, Models, and Views. Look closely and you will see that the Controllers names are associated with the folders in the Views folder. AccountController maps to Views\Account while HomeController maps to Views\Home. Views that are shared throughout the application are saved in the Views\Shared folder.

Let's take a look.

Student-Course-Admin

The first part of the application allows the user to look up a student by ID. As we can see from this screen shot the student with an ID of 1 is Jeanine Abbott. There are many steps involved in doing this using HTML, CSS and jQuery, so let's dive in.

Index.aspx has the following code:

1:

2: Find student by ID

3:

4:

5: <img src="../../Content/Images/ajax-loader.gif" class="ajaxLoader"

6: alt="ajaxloader" />

7:

8:

9:

10:

11:

12:

13:

14:

15:

16:

17:

18:

19:

20:

21:

22:

23:

24:

25:

26:

27:

28:

29:

30:

31:

32:

First Name Last Name Email Submit Date Approved Approved Date

33:

34:

The next piece is in the HomeController where we have a method called GetStudent(int id)

1: private readonly CourseEntities _db = ModelHelper.CourseEntities;

2: public JsonResult GetStudent(int id)

3: {

4: var student = (from s in _db.Students

5: where s.Id.Equals(id)

6: select s).FirstOrDefault();

7:

8: if (student == null)

9: return Json("error:Student not found.", JsonRequestBehavior.AllowGet);

10:

11: var singleStudent = new SingleStudent

12: {

13: Id = student.Id,

14: FirstName = student.FirstName,

15: LastName = student.LastName,

16: Email = student.Email,

17: SubmitDate = student.SubmitDate.ToShortDateString(),

18: Approved = student.Approved.ToString(),

19: ApprovedDate = string.Empty

20: };

21:

22: if(student.ApprovedDate.HasValue)

23: singleStudent.ApprovedDate = student.ApprovedDate.Value.ToShortDateString();

24:

25: return Json(singleStudent, JsonRequestBehavior.AllowGet);

26: }

The third piece of the puzzle is in the CSS. Looking at the ASPX code there are two div elements with classes of "studentData " and "errorMessage". In the CSS for this project these two classes have been defined as:

1: div.studentData{display:none}

2: div.errorMessage{display:none;color:Red;font-weight:bold;}

This makes these elements, and any elements contained within them to not be displayed when the page is first rendered.

The last piece to come into play is the JavaScript and jQuery. It is important to know that when adding your script references to your page, to make sure they are in the correct order. When you are going to use jQuery in your application and additional JavaScript files, the reference to jQuery needs to be first.

1:

2:

3: