.在asp.net mvc4的当前上下文中不存在RouteUrl
本文关键字:上下文 不存在 RouteUrl asp net mvc4 | 更新日期: 2023-09-27 18:06:05
我在url(<a href="@Url.RouteUrl....
)上得到错误。错误是在Url字。错误是url在当前上下文中不存在它在另一个视图页
@helper GetTreeView(Abacus_CMS.Models.AbacusModel siteMenu, int parentID)
{
foreach (var i in siteMenu.AbacusMenuList.Where(a => a.ParentCatagoryId.Equals(parentID)))
{
<li>
@{ var submenu = siteMenu.AbacusMenuList.Where(a => a.ParentCatagoryId.Equals(i.Id)).Count();}
@if (submenu > 0)
{
<li style="margin-left: -6px;">
<a href="@Url.RouteUrl("AbacusPage", new { catname = HttpUtility.UrlEncode(i.Name.Replace(' ', '-'))})" id="@i.Name.Replace(' ', '-').ToLower()">@i.Name
<i class="icon-user"></i><span class="title" style="margin-left: -24px;">@i.Name</span>
<span class="arrow " style="height: 4px;"></span>
</a>
<ul class="sub-menu">
@treeview.GetTreeView(siteMenu, i.Id)
@* Recursive Call for Populate Sub items here*@
</ul>
</li>
@*<span class="collapse collapsible"> </span>*@
}
else
{
<a href="@Url.RouteUrl("AbacusPage", new { catname = HttpUtility.UrlEncode(i.Name.Replace(' ', '-')), style="margin-left: 30px;"})" id="@i.Name.Replace(' ', '-').ToLower()">@i.Name
</a>
}
</li>
}
}
如何解决??
静态UrlHelper
-实例" Url
"不是在MVC helper的上下文中定义的。但是您可以通过Html.ViewContext.Controller
或在Html的帮助下创建实例来获得自己的实例。ViewContext(在链接的SO帖子中描述)。
你可以这样做
@helper MyHelper()
{
UrlHelper url= ((Controller) Html.ViewContext.Controller).Url;
<span>@url.RouteUrl(new {Controller = "Home", Action = "Action"})</span>
}
这里给出了一些很好的帮助方法:
应用于你的代码:
@helper GetTreeView(Abacus_CMS.Models.AbacusModel siteMenu, int parentID)
{
UrlHelper url= ((Controller) Html.ViewContext.Controller).Url;
foreach (var i in siteMenu.AbacusMenuList.Where(a => a.ParentCatagoryId.Equals(parentID)))
{
<li>
@{ var submenu = siteMenu.AbacusMenuList.Where(a => a.ParentCatagoryId.Equals(i.Id)).Count();}
@if (submenu > 0)
{
<li style="margin-left: -6px;">
<a href="@url.RouteUrl("AbacusPage", new { catname = HttpUtility.UrlEncode(i.Name.Replace(' ', '-'))})" id="@i.Name.Replace(' ', '-').ToLower()">@i.Name
<i class="icon-user"></i><span class="title" style="margin-left: -24px;">@i.Name</span>
<span class="arrow " style="height: 4px;"></span>
</a>
<ul class="sub-menu">
@treeview.GetTreeView(siteMenu, i.Id)
@* Recursive Call for Populate Sub items here*@
</ul>
</li>
@*<span class="collapse collapsible"> </span>*@
}
else
{
<a href="@url.RouteUrl("AbacusPage", new { catname = HttpUtility.UrlEncode(i.Name.Replace(' ', '-')), style="margin-left: 30px;"})" id="@i.Name.Replace(' ', '-').ToLower()">@i.Name
</a>
}
</li>
}
}