我有一个asp.net Webforms网站,我正在尝试将MVC集成到 . 我快到了,但我遇到了一些问题 .

What I did so far:

添加了以下参考:

  • System.Web.Routing

  • System.Web.Abstractions

  • System.Web.Mvc

更新了根Web.config以在运行时加载三个程序集 .

添加目录:

  • 意见

  • App_Code \ Controllers

更新了Global.asax并配置了路由:

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 = "" }           
            );
    }

到现在为止还挺好 .
我右键单击Controllers文件夹,添加一个"HomeController",像这样,运行网站,它的工作原理!

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...";
    }    
}

现在的问题是:

我更新HomeControler以使用View,就像这样,但它不起作用 .

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

为了创建视图,我在“Views”中创建了一个名为“Home”的目录 . 在“Home”里面我添加了一个新的“空页(Razor v3)”,名为“Index.cshtml”:

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

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>View Template!</p>

第一个问题是这一行:

ViewBag.Title = "Index";

VS表示“当前上下文中不存在名称'ViewBag'”

第二个问题是,当我运行网站时,我收到以下错误消息:

未找到视图“索引”或其主文件 . 搜索了以下位置:〜Views / Home / Index.aspx~ Views / Home / Index.ascx~ Views / Shared / Index.aspx~ Views / Shared / Index.ascx

我知道可以将Webforms网站与MVC页面集成 .
看起来我的配置是正确的 . 我可以成功添加一个控制器并获得所需的结果 .
但是,如何让我的Controller使用View?