0

I have an asp.net Webforms website that I'm trying to integrate MVC to. I'm almost there, but I'm having some problems.

What I did so far:

Added references to:

  • System.Web.Routing
  • System.Web.Abstractions
  • System.Web.Mvc

Updated the root Web.config to load the three assemblies at run time.

Added directories:

  • Views
  • App_Code\Controllers

Updated the Global.asax and configured routing:

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

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
        routes.MapRoute(
           "Default",
           "{controller}/{action}/{id}",
           new { controller = "Home", action = "Index", id = "" }           
            );
    }

So far so good.
I right-click the Controllers folder, add a "HomeController", like this, run the website and it works!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

public class HomeController : Controller
{
    public string Index()
    {
        return "This is my <b>default</b> action...";
    }
    public string Welcome()
    {
        return "This is the Welcome action method...";
    }    
}

Now the problem:

I update the HomeControler to use a View, like this, but it doesn't work.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }  
}

To create the view, I created a directory inside "Views" called "Home". Inside "Home" I added a new "Empty Page (Razor v3)", called "Index.cshtml":

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>View Template!</p>

The first problem is with this line:

ViewBag.Title = "Index";

VS indicates that "The name 'ViewBag' does not exist in the current context

The second problem is that when I run the website, I get the following error message:

The view 'Index' or its master was not found. The following locations were searched:
~Views/Home/Index.aspx
~Views/Home/Index.ascx
~Views/Shared/Index.aspx
~Views/Shared/Index.ascx

I know it is possible to integrate a Webforms website with MVC pages.
It appears like my configuration is correct. I can successfully add a Controller and get the desired result.
BUT, how do I get my Controller to use a View?

Administrateur
  • 891
  • 4
  • 13
  • 29

0 Answers0