Introduction
First of all don’t confuse with injecting keyword with Dependency Injection. It simply means that I am going to use MVC architecture into ASP.NET web forms application.<o:p>
I know this is not a big issue to inject MVC architecture into ASP.NET project but many times it helps us. But now this is possible and I hope you will definitely happy to learn the way to inject MVC architecture in to ASP.NET as I was!
Background
This article basically useful for those developers who have to work in ASP.NET Web Forms application but they are not a good in ASP.NET Web Forms. <o:p>
So no need to worry about this….I hope after this article you can also use the same concepts into your application if you are also facing the same problem….:)<o:p>
Contents
- Introduction
- Background
- Why should I have to inject?
- Quick introduction to ASP.NET MVC architecture
- Why ASP.NET MVC architecture?
- Steps to implement
- Step1: Create a sample project with web forms.
- Step2: Adding MVC required references into our sample project
- Step3: Adding MVC folders and its contents.
- Step4: Adding MVC default CSS file and register its reference into _Layout.cshtml
- Step5: Adding new Web.config file & updating old one.
- Step6: Registry files for routing, Scripts and CSS.
- Step7: Running the project.
- Sample Project Code
- Conclusion
Why should I have to inject?<o:p>
Being a team we are always facing some issue with developers who have good technical knowledge but due to rapid changes in technology, it becomes very difficult to update ourselves. So it might be possible that a team may have such members who know ASP.NET very well but not MVC & also some with ASP.NET MVC but not comfortable with ASP.NET web forms. In such case we need an environment which allows both users to develop modules with their own way within same project.<o:p>
That was a simple case when we can inject but we have lots more:<o:p>
- Tight Coupling: It prevents the concept of reusability of code.
- Not flexible to handle data on view.
- Hard to handle unit testing due to complex relationship.
So here we can use advantage of both the architectures.<o:p>
Note: I never say we always use MVC but it is possible if you really wanted to inject MVC architecture into your running ASP.NET web forms project.<o:p>
Quick introduction to ASP.NET MVC
The MVC (Model-View-Controller) nothing but an application design pattern where every component has its own responsibility develop application.<o:p>
Model: This component is responsible for maintaining state & simply can say carrying data from View to Controller or Controller to View. <o:p>
View: This component is responsible for displaying the application's user interface. Basically view can use model state values to display on UI as per user request.<o:p>
Controller: This component is responsible for handling end user interaction, manipulating the model on server, and ultimately making decision for which view must be rendered on UI.<o:p>
These are the simple MVC application’s principal that must be following while implementing the MVC architecture. SO Microsoft comes with all these concepts in ASP.Net MVC application.<o:p>
Why ASP.NET MVC architecture?
The ASP.NET MVC Framework has the following advantages over ASP.NET Web Forms approach. I hope this is not in the scope but we can discuss little bit:
Tight Coupling è Separation of concern
The main concern with ASP.NET Web Forms approach is its complexity with code behind files i.e., it leads developer to use tight coupling concepts.
Whereas in ASP.NET MVC the application is divided into Model, View and Controller component which make developer easier to manage the application complexity.
Test Driven Application Developement è Better Support
MVC application is better support to test-driven application development.
Less Reusable è Improve Reusability
ASP.NET MVC application components were designed to be pluggable and extensible and therefore can be replaced or customized easier then Web Forms.
You can find more differences over internet; I’ve listed only important points that may lead to create that article.
Steps to implement
Step1: Create a sample project with web forms:
Now in solution explorer we have only one web.config file and one global. asax file which are responsible for settings as well as how the application will start for ASP.NET web forms application.
Step2: Adding MVC required references into our sample project
Now, the Asp.Net application doesn’t have all references what MVC application required to run that’s why moving forward we need to add those references in our solution.<o:p>
These references are (ignore if already added any of them in your application):<o:p>
System.Web.Mvc
System.Web.Razor
System.Web.Http<o:p>
You can simply add these references by using the steps below:<o:p>
References => Add References => Assemblies => Search the same name and select valid version say 4.0 => Click OK <o:p>
System.Web.Optimization<o:p>
For this reference you need to install nugget package. For more detail fallow the link below: <o:p>
http://stackoverflow.com/questions/9475893/how-to-add-reference-to-system-web-optimization-for-mvc-3-converted-to-4-app
See the snapshot below for your reference to manage nuget package for the same:<o:p>
I am not going to explain these assemblies in detail because I know you are a MVC developer and you know very well about the use of these assemblies.<o:p>
After adding all these references you can just make sure in Reference folder here: <o:p>
Step3: Adding MVC folders and its contents:
To inject MVC architecture, we need to add all folders that MVC uses like App_Start, Controllers, Model and Views etc.<o:p>
You can simply create empty MVC application and just copy and paste all those files and their content in asp.net application where you are going to inject.<o:p>
In snapshot you can find out the required files and folders:<o:p>
Step4: Adding MVC default CSS file and register its reference into _Layout.cshtml
If you wanted to use your MVC CSS file into your running ASP.NET Web Forms then just copy and paste them into running application and set their references into _Layout.cshtml file.
In our case both file have the same name (Site.css) that’s why I have renamed that file to MVCSite.css and copied that file. <o:p>
Step5: Adding new web.config file & updating old one.
To get all MVC application setting we need MVC application configuration file i.e. Web.config file.
Now we have two Web.config files
- Asp.net default &
- MVC config file
Many new developers get confused with the two web.config files, they always think that any application can only have one web.config file but this is not true.
We can have multiple web.config file in application but different directory means we cannot have two web.config file within the same directory.
In the snapshot below I have added the MVC web.config file:
Now you need to update the ASP.NET Web Forms Web.config file with the settings below:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http:
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-AspWithMvcSample-20141229152959;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-AspWithMvcSample-20141229152959.mdf" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<!-- New -->
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AjaxControlToolkit" publicKeyToken="28f01b0e84b6d53e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.51116.0" newVersion="4.1.51116.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Step6: Registry files for routing, Scripts and CSS:
Now time came when we’ll tell the asp.net engine that you must fallow the one new route to map the user request as in MVC. This means we are going to register route for MVC pattern also.<o:p>
See the code snippet below:<o:p>
void Application_Start(object sender, EventArgs e)
{
AuthConfig.RegisterOpenAuth();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I have commented out others because I am not going to use them.<o:p>
Step7: Running the project.
Just create a simple aspx page and add a button and write the code below on button click event:
protected void btnRedirect_Click(object sender, EventArgs e)
{
Response.Redirect("/Home/Index");
}
This will redirect to Home Controller on Index action method.
Sample Project Code
I have already attached the sample project for your reference. You can simply download and use the sample code & its settings in your application.
Conclusion
I hope now you can able to use the same mechanizes to inject the MVC into your ASP.NET web forms application. You can let me know in case any doubt queries or concerns. I’ll be happy to receive and will get back to you as earliest.