我有PartialView
广泛使用ViewContext.Controller.ValueProvider.GetValue("action").RawValue
,这是一个片段:
<div class="@(ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "AddQuestion" ? "selectedItem" : "unselectedItem")">
@Html.ActionLink("Add a Question", "AddQuestion", new { topicId = ViewBag.topicId })</div>
<div class="@(ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "AddSubTopic" ? "selectedItem" : "unselectedItem")">
@Html.ActionLink("Add (Sub) Topic", "AddSubTopic", new { topicId = ViewBag.topicId })</div>
<div class="@(ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "AddResource" ? "selectedItem" : "unselectedItem")">
@Html.ActionLink("Add a Resource", "AddResource", new { topicId = ViewBag.topicId }) </div>
它继续这样......
我可以将动作名称保存在.cshtml中吗? (将它保存在ViewBag中对我来说似乎并不自然,因为.cshtml本身提供了这些信息)
答案 0 :(得分:3)
@{ var actionName = ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString(); }
<div class="@(actionName == "AddQuestion" ? "selectedItem" : "unselectedItem")">
@Html.ActionLink("Add a Question", "AddQuestion", new { topicId = ViewBag.topicId })</div>
<div class="@(actionName == "AddSubTopic" ? "selectedItem" : "unselectedItem")">
...
但创建一个HtmlHelper
可能会更清晰public static HtmlString CssClassForAction(this HtmlHelper helper, string action) {
var actionName = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
return new HtmlString(actionName == action ? "selectedItem" : "unselectedItem");
}
并在您的视图中
<div class="@Html.CssClassForAction("AddQuestion")">
@Html.ActionLink("Add a Question", "AddQuestion", new { topicId = ViewBag.topicId })</div>
<div class="@Html.CssClassForAction("AddSubTopic")">
...