ASP.NET MVC 5 的默认视图引擎是 Razor 引擎。以下是一个使用 Razor 引擎渲染视图的示例代码:
在控制器中:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
在视图中(例如 Views/Home/Index.cshtml):
@{
ViewBag.Title = "Home Page";
}
@ViewBag.Title
Welcome to the home page!
上述代码使用 Razor 引擎将视图呈现在浏览器中。若要在控制器中使用其他视图引擎,可以使用 View 方法的重载,在方法中指定所需的视图引擎。例如,要使用 Web Forms 视图引擎:
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index", "_Layout", null, "~/Views/Home/_MyWebFormsViewEngine.cshtml");
}
}
@ViewBag.Title = "Home Page"; }
Welcome to the home page!
这将呈现 Views/Home/Index.cshtml 视图,使用 Views/Shared/_Layout.cshtml 作为共享布局,并且将模型设置为 null。注:_MyWebFormsViewEngine.cshtml 是自定义视图引擎的文件名。