Best way to intregrate ASP.NET MVC with ASP.NET? [duplicate] - asp.net

Is it possible to create a MVC root application (Portal with masterpages and themes) and add a couple of WebForms based subprojects (we already have an existing WebForms application that we would like to integrate into the Portal)?
How would you centralize navigation (sitemaps, url routing)?
How would you share the masterpages?
How would you refer to resources (~ issues etc.)?

Combining web forms with MVC is entirely possible. See this blog post by Scott Hanselman for an introduction.
Sharing master pages: see this StackOverflow question
routing: In ASP.Net 4.0, routing has been enabled for web forms page routes (scottgu's blog)

For reference I managed to accomplish this task yesterday - add MVC functionality to an existing WebForms website, that is - so thought I would write in case it is of any use to anybody.
People say: "the best way is to rewrite your web forms application as MVC" but there is often no business case for this when the application is well established and has grew over time to be quite a monster (that still works well I might add). In my case, we had been asked to implement a new function into this application - and having been developing in MVC on other projects recently - I wanted to build this new function in MVC. This is what I did:
Create a new ASP.NET MVC 4 Application and selected the Empty Template (with Razor)
Once loaded, right-clicked References > Browse and then navigated to the Bin folder of my existing website. I then added in the DLL's I was using in the existing site. For reference, I am using AjaxControlToolkit so decided to add in the latest one from NuGet. This should then auto-update the web.config file
I then opened up Windows Explorer and navigated to the root folder of my existing website. Using Visual Studio, I then replicated the top-level folder structure of the existing site (minus the Bin folder) resulting in the 2 sites having the same top-level folders (but the new project having the MVC App_Start, Controllers, Models and Views folders also, but not Bin obviously).
Once setup, I copied the sub-folders and files from the corresponding top-level folder in Windows Explorer and pasted them into the solution. If you do it the way, the project allows you to copy in sub-folders and content directly, adding existing item via visual studio only copies in files thus saving time. Please note: for the root folder, I did NOT copy in web.config or Global.asax, but copied in all other files (like default.aspx, etc)
Once all content was copied, I opened up web.config in the new project and web.config in the existing site. I copied into the new web.config anything specific to the existing website (appSettings, connectionStrings, namespaces, membership info, etc). The same applied to the Global.asax files.
I attempted a build and fixed anything I'd missed.
Once everything was right (and I had shot down a few Yellow screens of death) I noticed that I got the page not found error when loading default.aspx. This is down to routing, here is the changes I made to the Routing info (located in Global.ascx MVC 3, or App_Start > RouteConfig.cs MVC 4):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// This informs MVC Routing Engine to send any requests for .aspx page to the WebForms engine
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx");
// Important change here: removed 'controller = "Home"' from defaults. This is the key for loading
// root default page. With default setting removed '/' is NOT matched, so default.aspx will load instead
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
With all these steps taken, the site loaded and ran as it always did, but I now have a ASP.NET WebForms and MVC hybrid. I am sure there are probably easier ways of accomplishing this task, but I tried other methods and failed. This way took me around 20 minutes and I was up and running... well sat and coding :)

Great answer above. The other thing you could consider is migrating from ASP.NET to ASP.NET MVC, in which case this post might help you migrate the project files.

I was too stucked in this situation, after all i got a solution which worked, first of all copy web.config in your views folder.
After that open Route.config(Routeconfig) file, there you will find one method RegisterRoutes, keep it as it is and create another method named RegisterRoutes2(), and copy paste the below method code from the mvc application:
public static void RegisterRoutes2(RouteCollection routes)
{...}
in some cases method name in mvc app would be RegisterRoutes.
If above code does not work, copy paste it from your machine’s mvc application.
Then, go to global.asax file, ther you will find RegisterRoutes() has been called, simple now , also call RegisterRoutes2().
And you are done, restart your application, or clean build, it will run.

Related

Using a view specific connection string in ASP.NET MVC

I upgraded an old website from ASP.NET to MVC recently and now I am running into a user login problem with one of my views. In the old situation I would have a separate web.config in the folder for that page that would set the connection string specifically for that page. Now I would like to do that in ASP.NET MVC as well, however the web.config in the specific views folder does not work. I also tried to change the web.config in the views folder, but maybe I did this in a wrong way because it did not work.
Does anyone have an idea how to accomplish the same result in ASP.NET MVC as I had in ASP.NET?
Why not use a separate configuration file, as explained in this MSDN article?
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files

Is there a way to tell a View in ASP.NET where to look for a Web.Config?

I've recently began a new project and I've decided to try to arrange the folders in a basic ASP.NET MVC project by feature (i.e. one folder would contain all Account files Models, View and Controller and another folder would contain Home Model, View and Controller etc...) instead of the default ASP.NET template. With this being said I quickly realized when I moved my views my controller was looking under the views folder. I fixed that but then my views were looking for the Web.Config and I fixed that by copying the views folder Web.Config into that folder. This is a solution but I want to know if I can point all my views to one Web.Config without having to have them all in the same folder.
Every folder in ASP.NET web application / website can have its own web.config file. Having said that, it is also necessary that the root folder of your application must have a web.config file based on which the application / website will be configured in the hosting environment.
Therefore, if you want to use different settings for different folders, you can place a separate web.config file with settings specific to folder in the any of the application folder.

MVC mobile site as subdomain in Webforms site

I have an existing webforms project, and I want to add my new MVC4 (mobile-focussed) site to it, as a subdomain. I also want it to be able to access the session variables from the webforms site. The idea is that the user logs in on the webforms site, sets a session variable and gets redirected to the mobile site (on the subdomain).
Initially I have added my MVC site to the webforms site, by making changes to the web.config, global.asax (for routing etc.), Controllers, Views and other folders at root level. This allows me to access the session variables. However because the webforms site is well-established (old) there are implications to changing the web.config (least of all re-testing). Hence the need for a subdomain.
Is it as easy as dropping my MVC site's folder into the Webforms root, so it has its own web.config, and changing the global.asax to route to it (and then creating a subdomain)? Will I still be able to access the session variables in the subdomain?
You can create a new project for the MVC mobile, configure the domain binding in IIS in something like that m.mydomain.com.
In the web.config of the two you define the same main domain:
<httpCookies domain=".mydomain.com"/>
Here start the difficoult task, you need to play attention to share the same machineKey in the two projects and probably you need to add an HttpModule depending on the selected session scenario.
Take a look on this article that can help you on some guidance.
To share the session, I implemented this from Microsoft. It is a HttpModule.
http://support.microsoft.com/kb/2527105
There was some additional work to do - I felt this article assumes you know a little about IIS. For example I had to manually add the module using IIS Manager.
I managed to get it to work in IIS7 by manually adding the Module using IIS Manager.
(Open IIS Manager -> select the application -> click modules (top right) -> add the SharedSessionModule by clicking 'Add managed module'.
Name: SharedSessionModule
Type: <namespace>.SharedSessionModule
(a dialog box said it could not find the assembly but at runtime it was fine)
Then Restart IIS.
The problem I then had was "session state is not available in this context" when serving up non-page items like images, .pdfs etc. Before I solved this, I have been asked to use my initial method (side-by-side) so I have not found how to change this BUT there are many suggestions on SO and other sites.

Hybrid MVC and Web Site application

I evaluating the MVC framework for my existing application. Trying to write a sample applicaiton where I need to navigate from MVc view to .aspx files and vice versa. The application does seems to be working. Not able to figure out where I am going wrong.
I have set up wild card mapping
I have set up .mvc mapping
I am using IIS6
I am using VS2008 with SP1
I added Controller directory to App_Code
I added Views directory to the web site application
MVC does not seem to be working well with web site application.
I do not know where to activate .mvc ? I do not know where to write the following code
HttpContext.Current.RewritePath(Request.ApplicationPath, False)
Dim httpHandler As IHttpHandler = New System.Web.Mvc.MvcHttpHandler()
httpHandler.ProcessRequest(HttpContext.Current)
HttpContext.Current.RewritePath(originalPath, False)
Can some one help me? I do not know how can I give my code so that you could review that.
This code would go into the Page_Load method in the code behind of the Default.aspx in the root directory.

How would you sprinkle-in ASP.Net MVC into an existing Web Site Project? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a legacy (haha) ASP.Net Webforms Web Site Project in Visual Studio 2008 SP1, that I would like to gradually introduce some MVC functionality into.
Most of the information I can locate on how to integrate ASP.Net MVC with WebForms seems to assume the use of a Web Application Project. However, it seems impossible to find information about how to retrofit an existing ASP.net Web Site Project with the ASP.Net MVC features.
I've reviewed Scott Hanselman's post and Chapter 13 of his upcoming book, both of which assume the Web Application Project type.
Is this possible? Does anyone have a how-to on this?
Well for starters adding MVC to a webforms project is pretty simple, to get the features in VS 2008 for MVC takes a little bit more work (still easy). First you want to be sure you reference the assemblies and are using .Net 3.5. Second you can create a controllers folder and views folder in your current web forms project. You can also create a simple controller with an index action. Then setup/configure the routes in the global.ascx file. You should be set from there. Check here for reference.
However you will only be able to create aspx pages with code behinds (you can delete those and enter the right inheritance class in the markup). To actually "convert" your project type so that you get the goodness of MVC and visual studio (add new view, goto controller, etc) is going to take some playing around with. My best advice is to create a new MVC project in VS 2008 and a new Web App project and compare the .csproj files in plain text. There is a long string value that tells VS the project template.
Believe me this does work. I have done it before on my own legacy projects. I don't remember how I found the project type "key" besides trial/error/elimination. ASP.Net MVC does play nice in the same project as webforms.
UPDATE: I think you can change to an MVC project type, which is still a web application by using these in the PropertyGroup of the .csproj file. Compare those to what you have and change the one that are differnt, be sure to copy/backup the file.
<ProjectGuid>{B99EC98A-1F09-4245-B00D-5AF985190AA9}</ProjectGuid>
<ProjectTypeGuids>{603c0e0b-db56-11dc-be95-000d561079b0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
Update 2: You wouldn't affect your project or impact it very much. If you are un easy about it make a backup and play around. If you encounter changes you will always have the backup. I was skeptical at first but was glad I went down the MVC path.
I thought I would give an updated answer using Visual Studio 2010 SP1 / NuGet / Scott Hanselman's totally unsupported utility.
Install MVC3 (w/ nuget)
http://www.asp.net/mvc/mvc3
Go to "Tools" menu in Visual Studio and select "Library Package Manager" \ "Package Manager Console"
Once console window appears, change the "Default Project" to be your webforms project.
Type "Install-Package AddMvc3ToWebForms" (http://nuget.org/List/Packages/AddMvc3ToWebForms)
This will add all necessary dlls, javascript files, web.config setting changes, etc to the project. If everything was successful, you should be able to press F5, navigate to "home" on your website, and see a sample form rendered by mvc: "Welcome to ASP.NET MVC, upgraded with a NuGet package in a totally unsupported way by Hanselman! No warranty!".
For a WebSite project, you just need to add Controllers to App_Code, not the root. You'll miss some VS goodness - as it doesn't know you're using MVC without the csproj file, but you'll actually get it working.
Just remember to inherit from Controller and ViewPage and you should be good.
I had a pretty big ASP.NET web site (not a web application) and wanted to add MVC3 to it. I had no option to change the type of the project so I had to go with the web site (asp.net 4.0).
I use a separate MVC project but not as it's own web application but as an assembly within my old web site.
Here's a rundown of what I did:
I created a new MVC3 web application in Visual Studio 2010, I used the empty template and the Razor view engine.
I added it to the solution with my existing web site.
I changed the output path for the assembly from the local bin
directory to the bin directory of my web site.
I removed the 'Content' and 'Scripts' folders from the MVC app. Both
content and scripts are already part of my web site and I can
reference these from MVC 'pages' as well.
I removed the Global.asax.* files from the project. I am using the Global.asax in the web site.
I copied the 'Views' folder and subfolders over to the web site. Because these are
actual files and not part of the assembly, they have to exist within the web site
not the project that builds the MVC assembly.
At this point I could have deleted the 'Views' folder from the MVC project but it is only in this project type that I get Visual Studio support for adding a new view. So I sometimes create a view here and then move it over to the web site.
When editing the cshtml files in my web site, I still get full Intellisense.
Added Routing to the web site. I just copied over some code from an MVC global.asax in the global.asax of my web site. We need some usings:
using System.Web.Mvc;
using System.Web.Routing;
In Application_Start we need:
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Then add the usual routing methods:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// your routes
}
Next add a few things to the web.config of your web site. In system.web under compilation we need the following assemblies:
<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>
Initially I also added some MVC namespace to web.config but it seems to work fine without them.
You do now create new routes in Global.asax of the web site, then add a corresponding controller in the MVC project and then back to the web site to add a view for it.
So you logic is all in a assembly while the views and the routing is defined in the web site.
You can still debug into the MVC controllers by setting break points there, but you debug by starting the web site.
If you use the suggested default route of MVC:
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
a call to www.mysite.com will serve up the content of the home controller/view not your old
default.aspx home page, so I just don't use such a route. If you routes conflict with existing physical folders and files, use constraints with regular expressions on the routes to exclude such conflicts.
Even though I use master pages in the web site, the actual html for the common page parts is created by code in another assembly. I could just call the same methods from my _ViewStart.cshtml or my base controller.
So far I have not seen any real negative about this approach.
As long as you setup the routing in web.config, setup the necessary directory structure, and add the correct routes in global.asax, you could theoretically add MVC items to any web project. So far as I know, those are the only requirements for it to work.
However, the combination of the two might be a bit confusing and difficult to maintain, long term. Maybe you could move all of the existing web forms site content into a subfolder to keep it out of the way and keep the root directory of the site clean to reduce the clutter and make things more clear.
If you want to add MVC 3 to an asp.net website rather than web project then Scott Hanselman's AddMvc3ToWebForms nuget package will get you 99% of the way there, but will throw an error during install you can saefly ignore (I think, at least in my tests this seems to be the case), and a couple of simple steps are needed after install.
Full details on http://delradiesdev.blogspot.com/2011/08/adding-mvc-3-to-aspnet-web-site.html
Mark (#delradie)
Something that I learn, while trying to migrate an MVC2 application is that your project needs a Default.aspx. I was tasked with adding some GUI functions to an existing Web Services project, and therefore there was no default.aspx. Took me a while to figure out why my routes weren't being setup.
The Microsoft .NET 4.0 exam on Web development (70-519) has almost this exact question in the prep materials. The answer, according to Microsoft then, is:
Convert the web forms website into a web application (i.e. webapp project).
Add references to "the ASP.NET MVC 2 assemblies" in the webapp's config file.
This info is in paid-for materials my employer purchased so there is not necessarily a web page stating it this clearly to which I could link.

Resources