How to get the controller name and data available in the base controller?

I have 2 questions.

First, the background:

I have PageController : Controller and SearchController : PageController

PageController is defined as:

 public class PageController : Controller { protected ISite Site; protected PageConfiguration PageConfiguration; protected override void Initialize(RequestContext rc) { this.Site = new Site(SessionUser.Instance().SiteId); this.PageConfiguration = this.Site.CurrentSite.GetPage(/* controller name */); base.Initialize(rc); } } 

I have a Site and PageConfiguration stored in PageController, because every page that implements PageController needs them

Question 1:
I am trying to port this from an existing ASP.NET application. what does the page name need to get a PageConfiguration object. Instead of the page name, I use the controller name instead. What is the best way for me to get this as a string?

Question 2:
I am trying to display a PartialView that relies on this data as follows:

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<PageConfiguration>" %> <%@ Import Namespace="tstFactsheetGenerator.Models.Panels"%> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% Html.RenderPartial("Search", new Search { PanelConfiguration = Model.Panels[0] }); %> </asp:Content> 

I see that when the RenderPartial () method is called the PageConfiguration Model, I need a panel. But in the constructor for the Search class, which PanelConfiguration is null.

Is there a better and more efficient way to make the data I need for this page? Thanks.

+4
source share
1 answer

Question 1:

 protected override void Initialize(RequestContext rc) { ... var controllerName = requestContext.RouteData.Values["controller"] ... } 

Question 2:

Since you use the class initializer syntax ( new { PanelConfiguration = ... } ), the PanelConfiguration will be null in the constructor of the Search class, but does it have a value? You should not use the PanelConfiguration property. In the Search part, it will be initialized. If you need to use it in the constructor (I don’t understand why you need it), you can add it as an argument to the constructor.

+6
source

Source: https://habr.com/ru/post/1313583/


All Articles