【问题标题】:Specify different body class for each page in partial view header在局部视图标题中为每个页面指定不同的正文类
【发布时间】:2017-08-06 01:57:17
【问题描述】:

我是 MVC 的新手,我想为每个视图设置不同的 body 类。 我的标题是部分视图,@RenderSection 不适用于它。

_Layout.cshtml:

    @{ 
        Html.RenderAction("GetHeader", "Main");
    }

    @RenderBody()

    @{
        Html.RenderAction("GetFooter", "Main");
    }

_HeaderLayout.cshtml:

    //...
    <body class=" here must be specified class different for each view">
    //...

主控制器:

    public class MainController : Controller
    {
        public ActionResult GetHeader()
        {
            return PartialView("~/Views/Shared/_HeaderLayout.cshtml");
        }

        public ActionResult GetFooter()
        {
            return PartialView("~/Views/Shared/_FooterLayout.cshtml");
        }
    }

有什么想法吗?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    我会通过两种方式做到这一点:

    1. 为应用中使用的所有视图模型创建一个基本 ViewModel 类,并为 BodyClass 添加一个属性,然后在部分视图中实现它。
    2. 在返回局部视图之前在ViewBag 字典中添加一个属性。

    示例: 1.基类

    public class BaseViewModel
    {
       public string BodyClass {get; set;}
    }
    

    用法:

    基类:

    局部视图:

    @model BaseViewModel
    ///...
    <body class="@Model.BodyClass">
    

    在控制器中:

     public ActionResult GetHeader()
     {
         var vm = new BaseViewModel { BodyClass= "test-class" };
         return PartialView("~/Views/Shared/_HeaderLayout.cshtml", vm);
     }
    

    ViewBag:

    public ActionResult GetHeader()
    {
         ViewBag[SomeConstantStringValue] = "test-class";
         return PartialView("~/Views/Shared/_HeaderLayout.cshtml");
    }
    

    局部视图:

    <body class="@ViewBag[SomeConstantStringValue]">
    

    请记住,您始终必须指定 ViewBag 值,否则会出错。

    【讨论】:

    • 感谢@mihail,但是HeaderLayout会在任何视图之前加载,并且BodyClass不能在MainController的GetHeader中设置,它必须单独设置在每个视图的每个控制器中。不是吗?
    【解决方案2】:

    Mihail Stancescu 的答案可能是最好的,但如果您不希望每个控制器方法都有一个视图模型,则可以使用辅助函数。不过,无论哪种方式,您都可能必须创建自己的方法来决定返回哪个类(请参阅下面的 BodyClassForTabAndMethod())。

    创建一个 Helper 类(如果您还没有合适的):

    public static class Helper
    {
        public static string BodyClassForTabAndMethod()
        {
            string[] selectedTabAndMethod = GetSelectedTabAndMethod();
    
            string bodyClass = "";
    
            // Change the below switch statements based upon the controller/method name.
            switch (selectedTabAndMethod[0])
            {
                case "home":
                    switch (selectedTabAndMethod[1])
                    {
                        case "index":
                            return "IndexClass";
                        case "about":
                            return "AboutClass";
                        case "contact":
                            return "ContactClass";
                    }
                    break;
                case "account":
                    switch (selectedTabAndMethod[1])
                    {
                        case "login":
                            return "LoginClass";
                        case "verifycode":
                            return "VerifyCodeClass";
                    }
                    break;
            }
    
            return bodyClass;
        }
    
        public static string[] GetSelectedTabAndMethod()
        {
            string[] selectedTabAndMethod = new string[2]; // Create array and set default values.
            selectedTabAndMethod[0] = "home";
            selectedTabAndMethod[1] = "index";
    
            if (HttpContext.Current.Request.Url.LocalPath.Length > 1)
            {
                // Get the selected tab and method (without the query string).
                string tabAndMethod = HttpContext.Current.Request.Url.LocalPath.ToLower();
    
                // Remove the leading/trailing "/" if found.
                tabAndMethod = ((tabAndMethod.Substring(0, 1) == "/") ? tabAndMethod.Substring(1) : tabAndMethod);
                tabAndMethod = ((Right(tabAndMethod, 1) == "/") ? tabAndMethod.Substring(0, tabAndMethod.Length - 1) : tabAndMethod);
    
                // Convert into an array.
                if (tabAndMethod.Count(s => s == '/') == 1)
                {
                    string[] split = tabAndMethod.Split('/');
                    selectedTabAndMethod[0] = split[0];
                    selectedTabAndMethod[1] = split[1];
                }
            }
    
            return selectedTabAndMethod;
        }
    
        public static string Right(string value, int length)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
    
            return ((value.Length <= length) ? value : value.Substring(value.Length - length));
        }
    }
    

    然后在你看来: &lt;body class="@Helper.BodyClassForTabAndMethod()"&gt;

    【讨论】:

      【解决方案3】:

      我为自己的问题找到了一个解决方案,非常简单:

      在 Global.asax: //或任何其他在开始时加载的类

          public static class WrrcGlobalVariables
          {
              //any other global variables...
      
              public static string BodyClass { get; set; }
          }
      

      在任何控制器中和返回视图/部分视图之前:

          public ActionResult Index()
          {
              //some codes...
      
              WrrcGlobalVariables.BodyClass = "HomePage";
      
              return View();
          }
      

      并在_HeaderLayout.cshtml中:

          <body class="@WrrcGlobalVariables.BodyClass">
      

      【讨论】:

        【解决方案4】:

        Mihail Stancescu 给出的两种方法都是正确的,但是还有另一种方法可以为其设置默认值并仅在需要时使用自定义值。此外,如果您所做的只是渲染部分而不需要任何需要子控制器的额外逻辑,那么您也应该为您的案例使用 RenderPartial 而不是 RenderAction。

        在_Layout.cshtml中

        @Html.Partial("_HeaderLayout")
        @RenderBody()
        @Html.Partial("_FooterLayout")
        

        在_HeaderLayout.cshtml中

        <body class="@ViewBag[SomeConstantStringValue]">
        

        在_ViewStart.cshtml中

        @{
            ViewBag[SomeConstantStringValue] = ViewBag[SomeConstantStringValue] ?? "default-class";
        }
        

        然后在任何视图或控制器中的任何位置设置此 ViewBag 值,这样您将确保有保证的默认值以防止空引用异常

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-26
          • 1970-01-01
          • 2017-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-18
          相关资源
          最近更新 更多