我想返回当前的动态视图,以允许我将一个CSS类附加到ActionLink,如果当前视图与ActionLink相同。C#MVC获取当前视图/动态模板
正如我传递的大部分环节,通过特定的途径,在这种情况下的页面,currentAction
永远是,网页在大多数情况下,尽管实际查看或叫的ActionResult返回模板。
因此,例如,如果url是http://mytestdomain.com/sport我想currentAction是运动而不是页面。
请参阅下面我的代码:
RouteConfig.cs
routes.MapRoute("Pages", "{mainCategory}/{subCategory}/{pageName}", new { controller = "Home", action = "Pages", subCategory = UrlParameter.Optional, pageName = UrlParameter.Optional });
的HomeController
public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
{
var currentController = htmlHelper.ViewContext.ParentActionViewContext.RouteData.GetRequiredString("controller");
var currentAction = htmlHelper.ViewContext.ParentActionViewContext.RouteData.GetRequiredString("action");
var currentView = htmlHelper.CurrentViewName();
var builder = new TagBuilder("li")
{
InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToHtmlString()
};
builder.AddCssClass("dropdown");
var actionSplit = actionName.TrimStart('/').Split('/');
actionName = actionSplit[0];
if (controllerName == currentController && actionName == currentAction)
{
return new MvcHtmlString(builder.ToString().Replace("a href", "a class=\"active\" href").Replace("</li>", "").Replace("Home/", ""));
}
return new MvcHtmlString(builder.ToString().Replace("</li>", "").Replace("Home/", ""));
}
public static string CurrentViewName(this HtmlHelper html)
{
return System.IO.Path.GetFileNameWithoutExtension(((RazorView)html.ViewContext.View).ViewPath);
}
public ActionResult Pages(string mainCategory, string subCategory, string pageName)
{
if (!string.IsNullOrEmpty(pageName))
{
subCategory = subCategory + "/" + pageName;
}
Page model;
using (CMSEntities)
{
model = (from f in CMSEntities.GetPage(1, mainCategory, subCategory, "Live") select f).FirstOrDefault();
}
return View(model.Template, model);
}
Navigation.cshtml
@Html.MenuLink(navigation.Title, "/" + Html.ToFriendlyUrl(navigation.Title), "Home")
我一直在使用var currentView = htmlHelper.CurrentViewName();
尝试,但这个总是返回导航作为ActionLink的正在从[ChildActionOnly] public ActionResult Navigation()
内视图中打了个比方@{ Html.RenderAction("Navigation", "Home"); }
从/共享/ _Layout.cshtml
任何帮助将不胜感激: - )