您真的需要使用 Javascript 来执行此操作吗?
让我们整理一下想法:
我有很多使用侧面板的页面
我在这里要做的是创建一个布局页面,您可以在需要添加此侧面板的所有视图上使用该布局页面。因此,您要在最终 html 输出中呈现此布局的视图应包括以下部分:
@{
ViewBag.Title = "Roles";
Layout = "~/Views/Shared/_SidePanelLayout.cshtml";
}
所以我正在考虑将所有页面中使用的侧面板的所有元素放在局部视图中并有选择地呈现
好的,我也会这样做,但是,在呈现选项时,我不会使用 javascript。我宁愿通过将模型发送到视图来发送唯一必需选项的 html。这是我要编码的过程:
1-当您请求使用此侧面板布局的页面时,您应该填写 ViewBag 属性(或模型)以传递页面名称。因此,假设您的 Home/Index 视图使用此布局,您可以执行以下操作:
public ActionResult Index()
{
ViewBag.PageName = "Home-Index"; //you could use constants or enums as best practice
return View();
}
在您的 _SidePanelLayout 视图的某个时间点,我会发出渲染操作调用。实际上,此渲染操作将使用该页面的特定选项渲染侧面板视图:
@{ Html.RenderAction("GetOptions", "SidePanelController", ViewBag.PageName); }
这意味着您将需要一个 SidePanelController 类,其方法将返回您的 SidePanelView(带有您请求的页面的特定选项):
public class SidePanelController: Controller
{
public ActionResult GetOptions(string pageName)
{
//you may want to change this List<string> for a list of objects that include
//the properties you need like url, name, tooltip, etc
List<string> menuOptions = new List<string>();
//Determine which options should be rendered
/* your code */
//return the view with the filtered options
return PartialView("_SidePanelView", menuOptions);
}
}
这样您就可以满足您的要求。它比使用 javascript 稍微复杂一些,但它是更强大的解决方案。
希望这会有所帮助。