Refactoring this PartialView (saving current action name in .cshtml)

喜欢而已 提交于 2019-12-08 08:24:35

问题



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


来源:https://stackoverflow.com/questions/6169644/refactoring-this-partialview-saving-current-action-name-in-cshtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!