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

丶灬走出姿态 提交于 2019-11-28 03:11:52
Kyle LeNeau

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.

  1. Install MVC3 (w/ nuget) http://www.asp.net/mvc/mvc3
  2. Go to "Tools" menu in Visual Studio and select "Library Package Manager" \ "Package Manager Console"
  3. Once console window appears, change the "Default Project" to be your webforms project.
  4. 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:

  1. Convert the web forms website into a web application (i.e. webapp project).
  2. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!