Refactoring this PartialView (saving current actio

2019-06-03 23:42发布

问题:


I have a PartialView which extensively uses ViewContext.Controller.ValueProvider.GetValue("action").RawValue, here's a snippet:

 <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>  

And it goes on like that...
Can I just save the action name in the .cshtml? (saving it in the ViewBag doesn't seem natural to me, as the information is available in the .cshtml itself)

回答1:

@{ 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")">
...

but it would probably be cleaner to create a 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");
}

and in your view

<div class="@Html.CssClassForAction("AddQuestion")">
@Html.ActionLink("Add a Question", "AddQuestion", new { topicId = ViewBag.topicId })</div>
<div class="@Html.CssClassForAction("AddSubTopic")">
...