简体   繁体   English

如何将参数解析到__layout.cshtml?

[英]How to parse parameters to __layout.cshtml?

How can I parse some parameters to __layout.cshtml? 如何解析一些参数到__layout.cshtml?

public class BaseInfo {
      public string ShowMenu {get; set;}
      public bool IsLoggedIn {get; set;}
      public string CustomerName {get; set;}
      .....
}

In __layout.cshtml, I would like to access these field, what is the best way for me to achieve this? 我想在__layout.cshtml中访问这些字段,对我来说最好的方法是什么?

Thanks! 谢谢!

You can add it as model 您可以将其添加为模型

@model NamespaceName.ModelsFolderName.BaseInfo

also you can use 你也可以用

ViewBag
ViewBag.CustomerName = BaseInfoObject.CustomerName;

to store any infornmation in it. 在其中存储任何信息。

Use child actions. 使用子动作。 Creating a custom WebViewPage class is just insane, and setting a model on your layout is just asking for trouble. 创建自定义WebViewPage类太疯狂了,在布局上设置模型只是自找麻烦。 If you do that, then every single view must then use that model or a subclass of that model, as well. 如果这样做,那么每个视图都必须使用该模型或该模型的子类。 Worst case scenario, you'll have at least one view that needs a different type of model; 最坏的情况是,您将至少有一个需要使用不同类型模型的视图; best case scenario, your entire business domain is defined by something you need in the UI (huge no-no). 最好的情况是,整个业务领域是由用户界面中需要的内容定义的(巨大的禁止)。

Child actions are like partials, in that you can just drop them anywhere in your layout or view, but unlike partials, they get their own separate context that doesn't effect anything else going on in the layout or view. 子动作就像部分动作一样,您可以将它们放在布局或视图中的任何位置,但是与部分动作不同​​,它们具有自己的独立上下文,不会影响布局或视图中发生的其他任何事情。

FooController.cs FooController.cs

public class FooController : Controller
{
    ...

    [ChildActionOnly]
    public ActionResult DisplayBaseInfo()
    {
        var baseInfo = new BaseInfo(); // pull from database or construct the instance however you like here
        return PartialView("_DisplayBaseInfo", baseInfo);
    }
}

_Layout.cshtml _Layout.cshtml

@Html.Action("DisplayBaseInfo", "Foo")

Put that call wherever you need to display the information in this instance. 将该呼叫放在您需要在此实例中显示信息的任何地方。 It doesn't matter what controller you put the child action in; 放置子动作的控制器无关紧要; just put it somewhere that makes sense to your application. 只需将其放在对您的应用程序有意义的位置即可。 Obviously, you'll need to create the partial view _DisplayBaseInfo.cshtml and then render the BaseInfo instance however you like there. 显然,您需要创建局部视图_DisplayBaseInfo.cshtml ,然后根据需要在其中渲染BaseInfo实例。 In that view you can set the model as BaseInfo and work strongly-typed, without affecting anything else. 在该视图中,您可以将模型设置为BaseInfo并进行强类型化,而不影响其他任何内容。

This way, there's zero dependencies. 这样, 依赖关系。 Everything can use standard MVC classes, without having to modify the page class or remember to have every view model inherit from some base class. 一切都可以使用标准的MVC类,而无需修改页面类或记住让每个视图模型都继承自某个基类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM