简体   繁体   English

MVC4:部分视图中的访问控制器属性

[英]MVC4: Access controller properties in partial view

Is it possible to access the property of a base controller from a partial view? 是否可以从局部视图访问基本控制器的属性?

I have the following setup: 我有以下设置:

public class BaseController : Controller
{
    private string ServerName
    {
        get
        {
            return Request.ServerVariables["SERVER_NAME"];
        }
    }
    private Entities.Client _Client { get; set; }
    public Entities.Client Client
    {
        get
        {
            return this._Client ?? (this._Client = this.HttpContext.Application["Client"] as Entities.Client);
        }
    }
    private Settings _Settings { get; set; }
    public Settings Settings
    {
        get
        {

            if (this._Settings == null)
            {
                this._Settings = new Settings(this.Client, this.Client.WebPageTemplateCapabilities != null ? SettingsType.XML : SettingsType.SQL);
            }

            return this._Settings;
        }
    }
}

All my controllers inherit BaseController, and in some of the views of the child actions of those controllers I render partial views. 我的所有控制器都继承了BaseController,在这些控制器的子操作的一些视图中,我渲染了部分视图。 Is there any way to access BaseController.Settings from one of those partial views? 有没有办法从其中一个部分视图访问BaseController.Settings?

Any information needed by the view should either be passed from the controller to the view and then further passed down from the view to the partials eg 视图所需的任何信息应该控制器传递到视图,然后进一步从视图传递到部分,例如

public ActionResult Index()
{
    return View(this.Settings);
}

In your view 在你看来

@model Settings

@Html.RenderPartial("SomePartial", Model)

In your partial 在你的部分

@model Settings

// use settings

All my controllers inherit BaseController, and in some of the views of the child actions of those controllers I render partial views 我的所有控制器都继承了BaseController,在这些控制器的子操作的一些视图中,我渲染了部分视图

In that case, you would just need to pass the model in from the controller eg 在这种情况下,您只需要从控制器传递模型,例如

public ActionResult SomeAction()
{
    return PartialView("SomePartialView", this.Settings);
}

I ended up doing this: 我最终这样做了:

@{
    var settings = (ViewContext.Controller as BaseController).Settings;
}

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

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