简体   繁体   中英

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. Is there any way to access BaseController.Settings from one of those partial views?

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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