Archive for the ‘ASP.NET’ Category

ASP.NET 4.5 has introduced model binding and strongly typed templates for ASP.NET server controls.This simplifies the way a plain .NET object can be bound as a datasource of a server control like a GridView.Let’s get started off with a simple example of how model binding works.

(more…)

Advertisements

This week I came across a problem related to structuring an ASP.NET MVC Web application one development team was facing. What they were trying to do was quite simple: to create a folder structure each having their own subfolders for View/Controller/Scripts/CSS etc. The application resources like JS/CSS etc. were not getting rendered properly. The issue was due to Web.config file lying under the subfolder, which when moved to the Views folder under that subfolder things went fine. The purpose of this post is not to discuss about the details of that problem and it’s solution.But to discuss about how we can easily structure our ASP.NET MVC Web application as per different modules, which is an obvious need for any large application.

ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions works fine for a smaller application. But for relatively bigger one there is a need to customize.The framework also provides enough provisions for the same.You can have your own controller factory to have custom ways to creating the controller classes and custom view engine for locating the rendering the views. But if the requirement is to structure the application to different subfolders as per modules or subsites  I think the use of “Area” in ASP.NET MVC will be helpful to create a streamlined application.

You can add an Area to a ASP.NET MVC project in VS as shown below.

area1

area2

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

area3

The code (auto generated) for the SalesAreaRegistration class is shown below:

public class SalesAreaRegistration : AreaRegistration 
{ 
    public override string AreaName 
    { 
        get 
        { 
            return "Sales"; 
        } 
    }

    public override void RegisterArea(AreaRegistrationContext context) 
    { 
        context.MapRoute( 
            "Sales_default", 
            "Sales/{controller}/{action}/{id}", 
            new { action = "Index", id = UrlParameter.Optional } 
        ); 
    } 
} 

System.Web.Mvc.AreaRegistration is the abstract base class use registering the areas into the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) needs to be overriden to register the area by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the necessary information (like Routes) required to register the area.

In Global.asax.cs Application_Start event we need to RegisterAllAreas() method as shown below:

AreaRegistration.RegisterAllAreas();  

The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

 

area4

Now I am trying to run the application and got the following error: [NOTE: This has nothing to do with areas but because I have two controllers with same type name i.e. HomeController]

Multiple types were found that match the controller named ‘Home’. This can happen if the route that services this request (‘{controller}/{action}/{id}’) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the ‘MapRoute’ method that takes a ‘namespaces’ parameter.

The request for ‘Home’ has found the following matching controllers:

AreasDemo.Controllers.HomeController

AreasDemo.Areas.Sales.Controllers.HomeController

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

public static void RegisterRoutes(RouteCollection routes) 
{ 
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute( 
                "Default", // Route name 
                "{controller}/{action}/{id}", // URL with parameters 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults 
                new String[] { "AreasDemo.Controllers" } 
            ); 
}

Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

 
<li>@Html.ActionLink("Sales", "Index", "Home", new { area="Sales"},null)</li>

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);

For navigating within the “Sales” area however routeValues will not be required.

ASP.NET MVC 4 (right now in Beta) has introduced the ASP.NET Web API , a MVC compliant framework for developing and hosting HTTP services which can be accessed from a variety of clients.In this post we will take how the ASP.NET Web API request processing pipeline works and HTTP request is passed between different processing stages. ASP.NET Web API can be hosted in IIS like a normal ASP.NET Web application and it can be also self hosted within a simple console application.For the sake of simplicity we will use a self hosted application here.

(more…)

ASP.NET 4.5 has introduced built-in support for bundling and minification of javascript and css resources.Here minification refers to the mechanism of compressing the javascript & stylesheet files thus reducing the size of data to transferred over the wire. The process of bundling involves combining multiple javascript/css files into one, thus reducing the number of HTTP calls made from the browser. The following post by Abhijit Jana gives a nice illustration of the feature covering the basics and  the advanced areas as well.

http://abhijitjana.net/2011/10/06/bundling-and-minification-in-asp-net-4-5/

Having read this, I was just thinking about these elements/classes under the System.Web.Optimization namespace are all stitched together to implement the bundling and minification functionality.There were some design level questions as well like is the bundled content cached once created at server side or the bundling is done for every request?.

(more…)

Those who have been working in ASP.NET MVC are already aware of the ASP.NET Routing feature introduced with .NET 3.5 SP1.But I have seen many who has developed a perception that ASP.NET Routing is something that can be used with only ASP.NET MVC.This is not the case.ASP.NET Routing comes under a separate namespace (System.Web.Routing) and assembly (System.Web.Routing.dll).This can be used with WebForms applications as well.But this required some custom coding to develop your RouteHandler as shown in the post below:

http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx

In ASP.NET 4.0, added capabilities are provided to make routing fully complete in order to work with WebForms.This is what I will be discussing in this post today.I will use simple webpage with 2 hyperlinks to demonstrate this feature.

(more…)

In my last post I had completed the demo of building a layered ASP.NET MVC application(the bookmark list application).This week I thought of adding the StructureMap container to that demo.I am quite new to StructureMap but I loved it’s usage of Fluent Interfaces and DSL a lot.I have primarily applied what I understood from it’s online documentation.I wanted to keep the option of plugging in another container later in this application.So I defined my own container interface as shown below:

    public interface  IContainer {
       
void AddInstanceConfig<I, T>(string key) where T:I; //Configures an instance with instance key,type and concrete type
       
void StartContainer(); //Starts the Container
       
object GetInstance<I>(string instanceName); //Returns an object instance based on the instance key/name
       
void DestroyContainer(); //destroys the container and releases the references

(more…)

Building the ASP.NET MVC Application

In the last 2 posts we have seen how to develop the Repository and WCF Services for our sample ASP.NET MVC application.This application contains the following Views:

  • Home/Index (Index.aspx) – Displaying the list of Bookmarks with options to Add New,Edit and Delete.
  • Add New (Create.aspx) – Displaying a blank form to enter the URL and Description.
  • Edit (Edit.aspx) – Displaying URL and Description of the selected bookmark.Only Description is editable.

There is a controller BookmarkController for all the above mentioned views.
(more…)