Channels ▼
RSS

Tools

What's New in Visual Studio 2010 & .NET 4 for Web Developers


ASP.NET MVC

The first good news with Visual Studio 2010 and .NET 4 is that ASP.NET MVC 2.0 is built-in. It's no longer an out-of-band release, though it is also available for earlier versions of Visual Studio and .NET 3.5 as a separate release.

Strongly Typed Templated Helpers. Templated Helpers provide a way to automatically build your user interface based on a data model that is market with attributes from the System.ComponentModel.DataAnnotations namespace. When you specify a data type, the template helper will render the value as the appropriate type using a control, so, for example, if your data type is a string, and you want to have a Create page that renders a TextBox letting users to enter the string, it's simply a case of using code such as this:


<%= Html.TextBox("Name") %>

Client and Server Validation Support. We've greatly improved Client and Server validation support, making it easier for you to build input forms, that will directly validate your data off your data models.

So, for example, you can create a class for a person like this, and use attributes from the System.ComponentModel.DataAnnotations namespace to specify which fields are required, and what their ranges are:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MVCValidate2
{
    public class Friend
    {
        [Required(ErrorMessage="Name is Required!")]
        public string Name { get; set; }
        [Required(ErrorMessage="Twitter Page is Required!")]
        public string TwitterPage { get; set; }
        [Required(ErrorMessage="Age is Required!")]
        [Range(0,140,ErrorMessage="Age should be between 0 and 140")]
        public int age { get; set; }
    }
}

A view that uses these provides a ValidationMessage like this:


          <p>
                <label for="Name">Name:</label>
                <%= Html.TextBox("Name") %>
                <%= Html.ValidationMessage("Name", "*") %>
            </p>
            <p>
                <label for="TwitterPage">TwitterPage:</label>
                <%= Html.TextBox("TwitterPage") %>
                <%= Html.ValidationMessage("TwitterPage", "*") %>
            </p>
            <p>
                <label for="age">age:</label>
                <%= Html.TextBox("age") %>
                <%= Html.ValidationMessage("age", "*") %>
            </p>

If you try to enter data that doesn't meet the validation criteria, and post it back, code in the controller like this will reject the invalid input and redisplay the page, this time with the validation messages rendered. You can see this in Figure 8.

[Click image to view at full size]
Figure 8: Using Validation in MVC.

Here's the code:


        [HttpPost]
        public ActionResult Create(Friend friendToCreate)
        {
            if (ModelState.IsValid)
            {
                // Add the data to the DB...it's valid
                // Code would go here.
                return Redirect("/");
            }
            return View(friendToCreate);
        }

Now you might be thinking, this is all very good, but it requires me to do a postback to the server before I get any validation. Modern, AJAX-based UIs are snappier than that and provide basic validation before you send it to the server. Well, the good news is that not only is this supported using .NET 4 and ASP.NET MVC 2, but that the same code that you used for Model-based validation can also be used to validate on the client. You don't need to write any extra logic -- just add some JavaScript and use a single line of code to activate it in your View. Here's what it would look like:


<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<% Html.EnableClientValidation(); %>

This keeps up with the principle of "Don't Repeat Yourself" (DRY) in development, allowing you to use the same attribution to have ASP.NET MVC create the code that will validate your data on both the client and the server.

Areas

ASP.NET MVC 2 adds the concept of "areas", which let you more easily partition and group functionality across an application. They provide a way to group controllers and views allowing you to build and maintain subsections of your application in relative isolation to other sections of your site. Each area is implemented as a separate MVC project which can then be referenced from the main application. It helps separate your code and concerns, as well as allowing diverse teams to work on a single application together. Figure 9 is an example of a Financial Portal where the main application (FinanceSite) supports areas for Fundamental Reference Data, Real Time and Trading.

[Click image to view at full size]
Figure 9: Areas in ASP.NET MVC.

Asynchronous Controllers

The controllers in ASP.NET MVC were synchronous in nature, and thus were not optimized for all scenarios. ASP.NET MVC2 allows you to use asynchronous controllers that you call, and they will call you back without blocking once their function is complete. So, for example, if your controller needed to call a network service to get some data back, and the transaction was long running, in ASP.NET MVC 1.0, your application would be blocked until the transaction was complete. In ASP.NET MVC 2.0, you can call the controller, and it will perform the network service call without blocking you, calling you back once its complete.

So, for example a synchronous controller for a stock quote from a Web service and returning it to the view may look like this:


public class QuoteController: Controller {
    public ActionResult GetQuote(string ticker) {
        QuoteService quoteService = new QuoteService();
        ViewStringModel quoteValue = quoteService.GetQuote(ticker);
        return View(quoteValue);
    }
}

This would be upgraded to an asynchronous controller like this:


public class QuoteController : AsyncController {
    public void QuoteAsync(string ticker) {
        AsyncManager.OutstandingOperations.Increment();
        QuoteService quoteService = new QuoteService();
        quoteService.GetQuoteCompleted += (sender, e) =>
        {
            AsyncManager.Parameters["quote"] = e.Value;
            AsyncManager.OutstandingOperations.Decrement();
        };
        quoteService.GetQuoteAsync(ticker);
    }
    public ActionResult GetQuoteCompleted(string quoteValue) {
        return View("Quote", new ViewStringModel
        {
            QuoteValue = quoteValue
        });
    }
}

If you're familiar with WebClient or Web Service calls, the paradigm is very familiar -- you specify the callback function, you make the asynchronous call, and you catch the return values in the callback function. In this case the callback function drives the view.

Conclusion

There are so many new goodies in Visual Studio 2010 and .NET 4 for web developers that it's impossible to list them all without writing several books. In this article we took you on a tour of some our favorite new features, from IDE improvements that let you be a more productive developer through to some of the great extras that AJAX, ASP.NET Web Forms and ASP.NET MVC developers can take advantage of. You saw the trend that Visual Studio has been taking -- making you more productive, and making your applications more Web friendly.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video