若需要在 Razor View 中使用导航链接,可以将以下代码添加到 View 文件顶部:
@using Microsoft.AspNet.Identity
然后可以使用如下代码添加导航链接和菜单:
@Html.ActionLink("Home", "Index", "Home") @Html.ActionLink("About", "About", "Home") @Html.ActionLink("Contact", "Contact", "Home")
若需要在控制器中实现导航链接,可以使用以下代码:
public ActionResult Index() { ViewBag.CurrentPage = "Index"; return View(); }
public ActionResult About() { ViewBag.CurrentPage = "About"; return View(); }
public ActionResult Contact() { ViewBag.CurrentPage = "Contact"; return View(); }
在 Layout 文件中使用以下代码,可以在导航菜单中高亮显示当前页面:
若 Razor View 中使用了未定义的变量或方法,会出现编译错误。例如,以下代码会导致错误:
@{ int count = myService.GetCount(); }
要解决这个问题,可以将 myService 注入到视图中,例如:
@inject MyService myService
若 Razor View 中需要使用 HTML Helper,可在 View 文件顶部添加以下代码:
@using Microsoft.AspNetCore.Html @using Microsoft.AspNetCore.Mvc.Rendering
注意:前提是在项目的依赖项中添加了对 Microsoft.AspNetCore.Mvc.ViewFeatures 的引用。
若控制器中的某个方法需要返回一个带有复