ASPHostCentral.com ASP.NET MVC Hosting BLOG

All about ASP.NET MVC 4.0 Hosting, ASP.NET MVC 3.0 Hosting and ASP.NET MVC Hosting articles

ASP.NET MVC Hosting :: Performing Validation in ASP.NET MVC Application

clock April 25, 2010 14:47 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site.

Abstract:

Validation is one of the most important aspects of an application. ASP.NET MVC framework provides multiple ways to validate the user input. In this article we are going to demonstrate how to perform validation in an ASP.NET application using Controller action, IDataErrorInfo and DataAnnotations methods.

Simple Validation:

The most simple way to perform validation is to perform it inside the Controller. The controller will be responsible for checking for the validity of the data. Let's check out the code for the view.

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Simple Validation</h2>
        
   <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   
   LastName: <%= Html.TextBox("LastName")%>
    
    <input type="submit" value="Save" />
    
    <% } %>

</asp:Content>

As, you can see the view is very simple and consists of FirstName and LastName TextBoxes. The submit button will submit the form and invoke the "SimpleValidation" action of the controller.

The controller used in this case is the HomeController. The SimpleValidation action is responsible for performing the validation on the data. The implementation of the SimpleValidation action is shown below:

public ActionResult SimpleValidation(Customer customer)
        {
            if(String.IsNullOrEmpty(customer.FirstName))
                ModelState.AddModelError("FirstName","FirstName cannot be blank!");

            if(String.IsNullOrEmpty(customer.LastName))
                ModelState.AddModelError("LastName","LastName cannot be blank!");

            if (!ModelState.IsValid)
                return View("SimpleValidation");

            return View("Confirmation");
        }

The SimpleValidation action accepts the Customer object as an input parameter. This is performed by Model Binders feature in ASP.NET MVC framework.

Inside the SimpleValidation action the ModelState.AddModelError method is used to populate the error collection of the model. The ModelState.IsValid property represents if there are any errors in the model. If the model is invalid then we simply return the current view which in this case is "SimpleValidation". If the model is valid then we return the "Confirmation" view.

Finally, make the adjustments in the view to display the errors. This is performed by the HTML helpers ValidationMessage as shown below:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Simple Validation</h2>
        
   <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
        
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   <%= Html.ValidationMessage("FirstName","*") %>
   
   LastName: <%= Html.TextBox("LastName")%>
    <%= Html.ValidationMessage("LastName","*") %>
    
    <input type="submit" value="Save" />
    
    <% } %>

</asp:Content>

Now, run the above page and click on the "submit" page without inputting the values for the FirstName and LastName. You will realize that the page was not submitted successfully since it was invalid. You can even make the errors more visible by using the ValidationSummary HTML helper as shown below:

 <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
        
    <%= Html.ValidationSummary("Errors") %>     
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   <%= Html.ValidationMessage("FirstName","*") %>
   
   LastName: <%= Html.TextBox("LastName")%>
    <%= Html.ValidationMessage("LastName","*") %>
    
    <input type="submit" value="Save" />
    
    <% } %>

Validation Using IDataErrorInfo:

T
he second method of performing validation in an ASP.NET MVC application is by using the IDataErrorInfo class. This method involves the model class to inherit from the IDataErrorInfo interface. The implementation is shown below:

 public class Customer  : IDataErrorInfo
    {
        private string _firstName;
        private string _lastName;
        private Dictionary<String,String> _errors = new Dictionary<string, string>();

        
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if(String.IsNullOrEmpty(value))
                    _errors.Add("FirstName","FirstName cannot be blank!");

                _firstName = value;
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                if(String.IsNullOrEmpty(value))        
                    _errors.Add("LastName","LastName cannot be blank!");

                _lastName = value;
            }
        }
        
        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                    return _errors[columnName];

                return String.Empty;
            }
        }

        public string Error
        {
            get { return String.Empty;  }
        }
    }

Using this method the controller action is simplified as the validation is now moved into the model itself. The implementation is shown below:

public ActionResult ValidationUsingIDataErrorInfo(Customer customer)
        {
            if (!ModelState.IsValid)
                return View("ValidationUsingIDataErrorInfo");

            return View("Confirmation");
        }

Using DataAnnotations
:

The DataAnnotations provides the most easiest way to perform validation in an ASP.NET MVC application. It uses attributes to perform validation.

You need to download "Data Annotations Model Binder Sample". Once, it is downloaded you need to build the solution in Visual Studio which will create the "Microsoft.Web.Mvc.DataAnnotations" and System.ComponentModel.DataAnnotations" assemblies. The final step is to set the DataAnnotations default binder to the Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();  in the Global.asax file as shown below:

protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();

        }

Now, in order to use the validation you will simply use the attributes on the model properties as shown below:

public class Customer
    {
        [Required(ErrorMessage = "FirstName cannot be blank")]
        public string FirstName { get; set; }

        [Required(ErrorMessage ="LastName cannot be blank!")]  
        public string LastName { get; set; }
    }

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: ASP.NET MVC Sample Application

clock April 22, 2010 22:08 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral.com and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site. We promise we’ll not disappoint you and we will give the best service for you. For us, the most important thing is you.

The application is intentionally simple. The goal was to provide members of the ASP.NET community with an application that they could use to quickly learn how to build new applications with ASP.NET MVC.

The Contact Manager application is an address book application. The application enables you to list, create, edit, and delete contacts.

We built the application over multiple iterations. With each iteration, we gradually improved the application. The goal of this multiple iteration approach was to enable you to understand the reason for each change.

Literation 1:
Create the application. In the first iteration, we create the Contact Manager in the simplest way possible. We add support for basic database operations: Create, Read, Update, and Delete (CRUD).

Literation 2:
Make the application look nice. In this iteration, we improve the appearance of the application by modifying the default ASP.NET MVC view master page and cascading style sheet.

Literation 3:
Add form validation. In the third iteration, we add basic form validation. We prevent people from submitting a form without completing required form fields. We also validate email addresses and phone numbers.

Literation 4:
Make the application loosely coupled. In this third iteration, we take advantage of several software design patterns to make it easier to maintain and modify the Contact Manager application. For example, we refactor our application to use the Repository pattern and the Dependency Injection pattern.

Literation 5:
Create unit tests. In the fifth iteration, we make our application easier to maintain and modify by adding unit tests. We mock our data model classes and build unit tests for our controllers and validation logic.

Literation 6:
Use test-driven development. In this sixth iteration, we add new functionality to our application by writing unit tests first and writing code against the unit tests. In this iteration, we add contact groups.

Literation 7:
Add Ajax functionality. In the seventh iteration, we improve the responsiveness and performance of our application by adding support for Ajax.

Each literation has an associated tutorial.

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Currently rated 1.0 by 1 people

  • Currently 1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: ASP.NET MVC Sample Applications, Open-Source Examples and Tutorials

clock February 10, 2010 16:22 by author Administrator

ASP.NET MVC is a free, fully supported, Microsoft product that enables developers to easily build great web applications. It provides total control over your HTML and URLs, enables rich AJAX integration, and facilitates test driven development.


Here is a list of various ASP.NET MVC Sample Applications demonstrating the new ASP.NET MVC Framework from Microsoft. If you like to have any of these applications hosted on a server, you can consider ASPHostCentral.com as your ASP.NET MVC hosting provider. With a package starting from only $4.99/month, you can have the latest ASP.NET MVC 2 RC framework running on our server.


CarTrackr

CarTrackr is a sample application for the ASP.NET MVC framework using the repository pattern and dependency injection using the Unity application block. It was written for various demos in presentations done by Maarten Balliauw. CarTrackr is an online software application designed to help you understand and track your fuel usage and kilometers driven. You will have a record on when you filled up on fuel, how many kilometers you got in a given tank, how much you spent and how much liters of fuel you are using per 100 kilometer. CarTrackr will enable you to improve your fuel economy and save money as well as conserve fuel. Fuel economy and conservation is becoming an important way to control your finances with the current high price


http://cartrackr.codeplex.com/


Codecampserver

This is the source code repository for CodeCampServer, a free, open source Code Camp management web application.

http://code.google.com/p/codecampserver/


Contact Manager

In this series of tutorials, Stephen Walther demonstartes how to use the ASP.NET MVC framework to build an entire Contact Manager application using unit tests, test-driven development, Ajax, and software design principles and patterns


http://www.asp.net/mvc/


FlickrXplorer

The project is an open source initiative to present users a fast photo explorer and search tool to browse millions of photos in flickr. The app is made with a bit of jQuery blend using Asp.net MVC and custom LINQ. The project also embodies a cloud computing scenario where the actual datastore lies millions of miles away invoked though simple API. The Application gives a nice starting point for Asp.net MVC, it also shows a strong integration of jQuery with Asp.net MVC as a client framework. It uses Athena (http://www.codeplex.com/LinqFlickr) LINQ to flickr API for fetching in and out data which is made on a custom LINQ provider toolkit made best for creating LINQ to Cloud APIs (http://www.codeplex.com/LinqExtender).

http://flickrxplorer.codeplex.com/


Kigg

KiGG is a Web 2.0 style social news web application developed in Microsoft supported technologies. The project uses ASP.NET MVC, Linq To SQL, MS Patterns & Practices Enterprise Library and Unity, jQuery, xUnit.net, Moq, HtmlAgilityPack, DotNetOpenId, and other 3rd party libraries


http://www.codeplex.com/Kigg


MVC StoreFront

I'm creating an ongoing series of webcasts and blog posts, documenting the building of an eCommerce storefront using ASP.NET MVC

http://blog.wekeroad.com/mvc-storefront/


Nerddinner

NerdDinner.com is an event management site so computer folks can meet and talk technology over a meal. It uses ASP.NET MVC along with jQuery, ASP.NET Ajax, Virtual Earth Javascript controls, and LINQ to SQL. It’s also a real site running at NerdDinner.com that you can use to schedule geek meet ups and nerd dinners in your neighborhood!

http://nerddinner.codeplex.com/


Oxite

Oxite is an open source, web standards compliant, blog engine built on ASP.NET MVC and LINQ To SQL. Oxite supports all the features we consider essential to a blog engine, including the MetaWebLog API (to allow you to use LiveWriter or similar tools to add/edit your posts), trackbacks, pingbacks, Sitemaps (for search engines), RSS and ATOM feeds (at the site, blog, tag and post level ... plus feeds of all new comments... great for the site owner), tags, integrated search, web based admin features (including editing posts, your site settings, etc.), email subscriptions for new comments, basic support to publish 'pages' (non-blog content) and more.

http://www.codeplex.com/oxite

Currently rated 2.3 by 4 people

  • Currently 2.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: Specifications and Functions

clock July 24, 2009 13:00 by author Administrator
The ASP.NET MVC Framework couples the models, views and controllers using interface-based contracts, thereby allowing each component to be easily tested independently. By default, the view engine in the MVC framework uses regular .aspx pages to design the layout of the user interface pages onto which the data is composed.

However, different View Engines can be used (for example, you can create a View Engine based on XSLT files. Additionally, rather than the default ASP.NET post back model, any interactions are routed to the controllers using the ASP.NET 3.5 SP1 Routing mechanism.
The ASP.NET MVC Framework is a Model-view-controller framework which Microsoft is adding to ASP.NET. It allows software developers to build a Web application as a composition of three roles: Model, View and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display it.

More information on Model View Controller (MVC) Framework or
ASP.NET MVC hosting plans, log on to http://www.asphostcentral.com/ASP-NET-MVC-Hosting.aspx or contact ASPHostCentral.com at http://www.asphostcentral.com


 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASPHostCentral.com :: How to Deploy an ASP.NET MVC Hosting Application

clock March 24, 2009 18:36 by author Administrator

If your hosting provider already has ASP.NET MVC 1.0 installed on the hosting server, deploying your MVC application is no different that deploying any ASP.NET Web application. However, if the hosting provider does not currently support ASP.NET MVC 1.0, you must upload the required MVC assemblies in the Bin folder of your deployed application.

After ASP.NET MVC is installed, the following assemblies are located in the global assembly cache (GAC) on your computer:

- System.Web.Mvc (the ASP.NET MVC assembly)
- System.Web.Routing (a .NET Framework assembly that is required by ASP.NET MVC)
- System.Web.Abstractions (a .NET Framework assembly that is required by ASP.NET MVC)

If your hosting provider has ASP.NET version 3.5 Server Pack 1 installed, you have to upload only the System.Web.Mvc assembly. If your hosting provider is using ASP.NET version 3.5 or an earlier version, you must deploy all the listed assemblies.

ASP.NET MVC runs in medium trust. Therefore, it should work with the medium-trust policies of most hosting providers. However, check with your hosting provider about trust policies.

We recommend that you use the Publish feature of Visual Studio to publish to a local folder and then upload the files to your hosting provider. You can then test exported files before you copy them to the hosting provider. If the hosting provider supports FTP, you can often skip this intermediate step and publish directly to the hoster's FTP server.


To deploy an ASP.NET MVC application

1. In Visual Studio, open the project that you want to deploy.
2. In Solution Explorer, expand the References node.
3. Select the following assemblies:
- System.Web.Mvc
- System.Web.Routing
- System.Web.Abstractions
4. In the Properties window, set Copy Local to True.
5. In Solution Explorer, right-click the project and click Publish.  The Publish Web dialog box is displayed.
6. In Target location (http:, ftp:, or disk path), browse to a local folder and click Open.
7. Select either Replace matching files with local copies or Delete all existing files prior to publish.
8. Under Copy, select one of the following, depending on your needs: Only files needed to run this application, All project files, or All files in the source project folder.
9. If your application contains files in the App_Data folder such as database files, select Include files from the App_Data folder.
10. Click Publish. All the files that are required in order to deploy the application are copied to the target folder.

 

11. Test your application by deploying the files to a staging server or virtual machine that does not have MVC installed. If you do not have access to a staging server or a virtual machine, you can uninstall MVC and then test the application locally.
12. Upload the application to the hosting provider.


ASP.NET MVC Hosting Provider

We recommend ASPHostCentral.com as your main ASP.NET MVC Hosting Partners simply because:

- You can host your ASP.NET MVC Project from as low as $4.99/month only
- 100% Customer Satisfaction Guarantee
- 24/7 Support Monitoring system with 30 Days Money Back Guarantee
- Up-to-date and top notch technology and control panel


This article is sourced from here.

Currently rated 1.6 by 49 people

  • Currently 1.571427/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASPHostCentral.com :: Hosting and Deployment of an ASP.NET MVC Application in IIS6 and IIS7

clock March 23, 2009 18:15 by author Administrator
When building any application, the chances are that the application will have to be deployed. This article describes how you can deploy and host an ASP.NET MVC application in an Internet Information Server (IIS6 and IIS7) platform.


Platforms that can be used

Theoretically, any web server capable of running ASP.NET web applications should be capable of running an ASP.NET MVC web application.

Supported platforms are Windows running any version of Internet Information Services (IIS), from version 5.1 on.
Some people managed to get ASP.NET MVC web applications running on Mono, an open source implementation of the .NET framework, but this is not officially supported.

Building an ASP.NET MVC web application also means building URL routes. URL routing is a key part of the ASP.NET MVC framework and is, therefore, required to run on the IIS server. Depending on the version of IIS being used, additional configuration may be required in order to be able to take advantage of URL routing.

Any ASP.NET MVC web application will be able to run on the following versions of IIS: 
IIS version Windows version Remarks
IIS 7.0 (integrated mode) Windows Server 2008Windows Vista (except Home Basic) No special configuration required
IIS 7.0 (classic mode) Windows Server 2008Windows Vista (except Home Basic) Special configuration required to use URL routing 
IIS 6.0 Windows Server 2003 Special configuration required to use URL routing
IIS 5.1 Windows XP Professional Special configuration required to use URL routing
IIS 5.0 Windows 2000 Special configuration required to use URL routing


Differences between IIS 7.0 integrated and classic mode

IIS 7.0 has been developed to be a flexible and scalable platform for hosting dynamic web applications including Microsoft ASP and ASP.NET.

When looking at ASP.NET, IIS 6.0 was built using ISAPI modules, requiring low-level C++ API calls and a lot of processing overhead when transferring an HTTP request to ASP.NET. For example, authentication was performed twice: once in IIS and once in ASP.NET. IIS 7.0. This introduced a whole new integrated model, which allowed ASP.NET applications to plug into the web server directly and actually become a part of the web server executable.



With classic mode, an HTTP request would be executed as follows:



As you can see, things such as authentication are performed twice, only for ASP.NET requests. Protecting an image from being displayed using ASP.NET authentication would be impossible in the classic mode! Using integrated mode, any HTTP request can be processed using ASP.NET modules and handlers such as authentication, making ASP.NET a full member of the IIS request processing pipeline.




IIS 7.0 provides support both for this new integrated mode and for the classic IIS 6.0 mode. The first option allows you to configure IIS 7.0 from within your web.config (which is preconfigured for the ASP.NET MVC framework); the latter requires some server-side configuration. To check whether an application is running in integrated or classic mode, follow these steps:

1.      Launch the Internet Information Services Manager.
2.      In the Connections tree view, select an application.
3.      In the Actions window, click on the Basic Settings link to open the Edit Application dialog box.
4.      Verify the selected Application pool. If DefaultAppPool is selected, your application runs in an integrated mode and natively supports the ASP.NET MVC framework. If Classic .NET AppPool is selected, your application runs in the classic mode, and more configuration is required. 


Hosting an ASP.NET MVC web application

If you or your web hosting provider have access to your web server's settings, a wildcard script map can be created in order to have full routing support. A wildcard script map enables you to map each incoming request into the ASP.NET framework. Be aware that this option passes every request into the ASP.NET framework (even images and CSS files!) and may have performance implications.If you do not have access to the web server's settings, you can modify the route tableto use file extensions. Instead of looking look like this:

/Products/All

URLs would look like this:

/Products.aspx/All

This way, no configuration of the web server is required. It is, however, necessary to make some modifications to the application's route table.You do not have to configure anything if your IIS 7.0 server is operating in integrated mode.


Creating a wildcard script map in IIS 7.0
 

Here is how you can enable a wildcard script map in Internet Information Services 7.0:
1.      Launch the Internet Information Services Manager.
2.      In the Connections tree-view, select an application.
3.      In the bottom toolbar, make sure that the Features view is selected.
4.      Double-click on the Handler Mappings shortcut.
5.      In the Actions window, click on the Add Wildcard Script Map button.
6.      Enter the path to the aspnet_isapi.dll file, which is usually located in: %windir%Microsoft.NETFrameworkv2.0.50727aspnet_isapi.dll.
7.      Enter the name ASP.NET MVC.
8.      Click on the OK button.

After doing this, any request for this specific web site will be executed by the ASP.NET engine


Creating a wildcard script map in IIS 6.0

Here is how you can enable a wildcard script map in Internet Information Services 6.0:

1.      Launch the Internet Information Services IIS Manager.
2.      Right-click on a web site and select Properties.
3.      Select the Home Directory tab.
4.      Near Application settings, click on the Configuration button.
5.      Select the Mappings tab.
6.      Near Wildcard application maps, click on the Insert button.
7.      Enter the path to the aspnet_isapi.dll file, which is usually located in %windir%Microsoft.NETFrameworkv2.0.50727aspnet_isapi.dll
8.      Uncheck the Verify that file exists checkbox.
9.      Click on the OK button.After following these steps, any request for this specific web site will be executed by the ASP.NET engine 


Modifying the route table to use file extensions

If you do not have access to your web server's settings and, therefore, cannot configure a wildcard script map, it is possible to modify the route table to use file extensions. Instead of looking like this:

/Products/All

URLs would look like this:

/Products.aspx/All

In the older versions of IIS, only certain requests are mapped to the ASP.NET framework. For example, only .aspx, .asmx, .ascx, and so on, are mapped to the ASP.NET framework. Extensions such as .htm, .jpg, .gif, and so on, are served directly by IIS without any ASP.NET processing being necessary. Because the .aspx extension is always mapped to the ASP.NET framework, it is an ideal candidate to trigger the routing engine
In the Global.asax file of the web application, modify the default route to look like this:

using System.Web.Mvc;
using System.Web.Routing;

namespace ModifiedRouteExample
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               "Default",                                      
             // Route name
              
               "{controller}.aspx/{action}/{id}",                    
            // URL with parameters
              
               new { controller = "Home", action = "Index", id = "" }
            // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

The key difference between the standard route table and this modified route table is the .aspx extension:

routes.MapRoute(
    "Default",
    "{controller}.aspx/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);


All of the URLs in your application should now work with a pattern such as {controller}.aspx/{action}. If you are using hard-coded hyperlinks, make sure that you modify these links. Hyperlinks that are generated using the ActionLink() method of the HtmlHelper class should be updated automatically.


Summary

In this article, we have learned which hosting platforms can be used to host an ASP.NET MVC web application. We've also seen the differences between IIS 7.0 integrated mode and classic mode. We've learned how to create a wildcard script map in both IIS 7.0 and IIS 6.0. As an alternative to configuring the web server, we have learned how to modify the route table to support ASP.NET routing on some hosting environments.


Where to go for ASP.NET MVC Hosting?


You can host your website on the ASP.NET MVC Framework at ASPHostCentral.com and you can do it by just paying $4.99/month

Currently rated 2.0 by 23 people

  • Currently 1.956522/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASPHostCentral.com :: Using ASP.NET MVC Routing to route the 404 Error Pages

clock March 19, 2009 21:51 by author Administrator
This article describes a way to use ASP.NET Routing to avoid 404 Not Found errors when changing folder structure or folder names in a web site.

What to do with obsolete links to your web site?

Having a web site means spending some time and efforts promoting the site on the Internet, making sure search engines indexed all the pages, trying to get exposure through blogs or discussion boards.

And then you get new idea and really need to restructure your site "change some folder names, move some pages, etc. What will happen with all those third-party links to your site you were so proud of? Do you want to lose them?

Route old URLs to new site structure

With arrival of .NET Framework 3.5 SP1 we got an elegant way of solving this problem ASP.NET Routing. Initially it was a part of ASP.NET MVC Preview 2, and now it is a part of the Framework.

The idea is to add special "Routs" to the site having single goal of processing requests to pages which are no longer present on the site. In its simplistic form the processing can happen in a single ASPX page responsible for proper handling of requests. Here is the example.

These parts you'll need in the project:

WebFormRouteHandler created by Chris Cavanagh representing IRouteHandler implementation, Global.asax file registering your Routs, web.config file where you register the WebFormRouteHandler , and Default.aspx page responsible for actual request processing.

Let's take a look at Global.asax.

    void Application_Start(object sender, EventArgs e)
    {
        // runs on application startup
        RegisterMyRoutes(System.Web.Routing.RouteTable.Routes);
    }
    private void RegisterMyRoutes(System.Web.Routing.RouteCollection routes)
    {

        // reference IRouteHandler implementation (example created by Chris Cavanagh)
        // see http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/
        var startPageRouteHandler = new WebFormRouteHandler("~/default.aspx"); 

        // exclude .axd to handle web services and AJAX without checking all routs
        // see http://msdn.microsoft.com/en-us/library/system.web.routing.stoproutinghandler.aspx
        routes.Add(new System.Web.Routing.Route("{resource}.axd/{*pathInfo}", new System.Web.Routing.StopRoutingHandler()));
       routes.Add(new System.Web.Routing.Route("{service}.asmx/{*path}", new System.Web.Routing.StopRoutingHandler()));
        
         // mapping:
        // extracts folder name and page name as items in HttpContext.Items
        routes.Add(new System.Web.Routing.Route("{folderName}/", startPageRouteHandler));
        routes.Add(new System.Web.Routing.Route("{folderName}/{pageName}", startPageRouteHandler
);
    }

Here we defined single route handler - default.aspx, as well as routing rules.

Rule #1:

routes.Add(new System.Web.Routing.Route("{folderName}/", startPageRouteHandler));

states that all requests to a URL with structure "http://mysite.com/something" will be processed by the default.aspx page if there was no actual "something" found on the site. For example, there is a RealPage.aspx page present on the site, so requests to http://mysite.com/RealPage.aspx will be processed by that page.

But if client requests RealPage2.aspx, that request will be processed by the default.aspx page according to the rule #1. Note that client will not be redirected to default.aspx, it will be just web server running code in default.aspx in response to the request. For the client the response will come from the RealPage2.aspx.

You can add as many routes as you want, for example rule #2:

routes.Add(new System.Web.Routing.Route("{folderName}/{pageName}", startPageRouteHandler));

stating that all requests to a URL with structure "http://mysite.com/somefolder/somethingelse" will be processed by the default.aspx page if there was no actual "somefolder/somethingelse" found on the site.

The code behind default.aspx shows how to extract those parts of the request. As you can see they will be placed in the HttpContext.Items collection.

        lblFolder.Text = Context.Items["folderName"] as string;
        lblPage.Text = Context.Items["pageName"] as string;

How it works in real life

Here is a real life web site actually using this technique - Digitsy Global Store. Besides handling obsolete URLs the ASP.NET Routing is being used to handle multiple languages on the site, switching CultureInfo on the fly:


   protected void Page_PreInit(object sender, EventArgs e)
    {
        CultureInfo lang = new CultureInfo(getCurrentLanguage());
        Thread.CurrentThread.CurrentCulture = lang;
        Thread.CurrentThread.CurrentUICulture = lang;
    }
    private static string getCurrentLanguage()
    {
        string lang = HttpContext.Current.Items["language"] as string;
        switch (lang)
        {
            case "france":
                return "fr-FR";
            case "canada":
                return "en-CA";
            case "germany":
                return "de-DE";
            case "japan":
                return "ja-JP";
            case "uk":
                return "en-GB";
            case "russia":
                return "ru-RU";
            default:
                return "en-US";
        }
    }

As you see, the default language is English, United States: "en-US". In internal links the site uses structure http://{sitename}/{language}/¦other things¦

So if you try http://digitsy.com/us/ you'll get US version, trying http://digitsy.com/japan/ will bring you Japanese one, and if you try http://digitsy.com/whatever " you'll not get 404 error, you'll get US version again.

ASP.NET Routing made restructuring of the site really easy. The folder structure "{language}/{index}/category/{categoryID}" was recently replaced by "{language}/{index}/shopping/{categoryID}". There supposed to be no "category" folder in the site structure anymore. But because of both routs pointing to the same handling page both folders "category" and "shopping" return valid responses.

Trying
http://digitsy.com/us/Electronics/shopping/541966  will use the rule:

routes.Add(new System.Web.Routing.Route("{language}/{index}/shopping/{categoryID}", categoryRouteHandler));

while trying
http://digitsy.com/us/Electronics/category/541966  will use:

routes.Add(new System.Web.Routing.Route("{language}/{index}/category/{categoryID}", categoryRouteHandler));

and both will resolve to the same route handling page.


Where to go for ASP.NET MVC Hosting?

You can host your website on the ASP.NET MVC Framework at ASPHostCentral.com and you can do it by just paying $4.99/month 

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!


Sign in