问题描述
|
为什么Html.ActionLink在以下代码中不起作用?这是app_code文件夹中的页面,
我试图从index.cshtml调用
LogOnUserControl.cshtml
@helper DisplayUserControl(){
如果(Request.IsAuthenticated){
<span>Welcome <strong>@User.Identity.Name</strong>!</span>
<span>[ {@Html.ActionLink(\"\",\"\",\"\")} ]</span>
}
else {
<span>[{@Html.ActionLink(\"\",\"\") }]</span>
}
}
这是index.cshtml中的代码行。如果我删除了Html.ActionLink语句,该站点本身将正常工作。是不是您不能在这样的嵌套页面中使用它们?我还能如何生成动态链接?
index.cshtml
@LogOnUserControl.DisplayUserControl()
解决方法
此操作链接的想法是什么?为什么要传递空字符串作为参数?我想您想生成SignIn,SignOut链接,不是吗?
另外,如果要在放置在
App_Code
文件夹中的共享帮助器中使用HTML帮助器,则将它们作为参数传递,因为它们不可用:
@using System.Web.Mvc.Html
@helper DisplayUserControl(System.Web.Mvc.HtmlHelper html) {
if (html.ViewContext.HttpContext.User.Identity.IsAuthenticated) {
<span>
Welcome
<strong>
@html.ViewContext.HttpContext.User.Identity.Name
</strong>
!
</span>
<span>[@html.ActionLink(\"SignOut\",\"Login\")]</span>
}
else {
<span>[@html.ActionLink(\"SignIn\",\"Login\")]</span>
}
}
并给助手打电话:
@LogOnUserControl.DisplayUserControl(Html)
就我个人而言,我从来没有使用过这样的助手(放在App_Code
文件夹中的助手)。当您拥有局部视图,编辑器/显示模板和Html.Action帮助器时,看不到它们的任何用途。
因此,例如,您可以定义部分(~/Views/Shared/_LogOnUserControl.cshtml
):
@if (User.IsAuthenticated) {
<span>
Welcome
<strong>
@User.Identity.Name
</strong>
!
</span>
<span>[@Html.ActionLink(\"SignOut\",\"Login\")]</span>
}
else {
<span>[@Html.ActionLink(\"SignIn\",\"Login\")]</span>
}
您将在布局中包括以下内容:
@Html.Partial(\"_LogOnUserControl\")