How can I set a variable on a _Layout page?

后端 未结 3 1544
温柔的废话
温柔的废话 2021-02-13 19:01

I have a view and I want to use a layout page. In the layout page I want to have a conditional banner which some of the view will turn on/off. Just wondering how I can do this?<

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 19:29

    I'm with you, Exitos: I avoid using ViewBag too. Aside from the silly name, I dislike the weak typing that comes along with it. There is a solution, but it's kind of involved, so bear with me.

    First, create a class to store the "display hints" that are to be passed to the layout. I creatively call this class "DisplayHints":

    public class DisplayHints {
      // anything that you want passed from a view to the layout goes here
      public bool ShowBanner { get; set; }
    }
    

    Then, create a class deriving from WebViewPage that will be the new base class of your views. Note how we have a property called DisplayHints that's stored in ViewData (which is available to the controller, the view, and the layout):

    public abstract class MyViewPage : WebViewPage {
      public DisplayHints DisplayHints {
        get {
          if( !ViewData.ContainsKey("DisplayHints") )
            ViewData["DisplayHints"] = new DisplayHints();
          return (DisplayHints)ViewData["DisplayHints"];
        }
      }
    }
    

    As a commenter pointed out below, ViewData is weakly-typed, just like ViewBag. However, there's no way I know of to avoid storing something in ViewData/ViewBag; this just minimizes the number of weakly-typed variables to one. Once you've done this, you can store as much strongly-typed information in DisplayHints as you want.

    Now that you have a base class for your views, in Web.config, we need to tell MVC to use your custom base class:

    
    

    It sounds like a lot of trouble, but you gain some serious functionality for all this work. Now in your view, you can set any display hint you want as follows:

    @{ DisplayHints.ShowBanner = true; }
    

    And in your layout, you can access it just as easily:

    @if( DisplayHints.ShowBanner ) {
      
    My banner....
    }

    I hope this helps!

提交回复
热议问题