ASP.Net Calling Site.Master method from web page not working - asp.net

I saw on several web pages how to interface to a public method defined in a master file from a web page call behind code that uses that master file.
(I am using ASP.Net 4.0 on Visual Studio 2012.)
The procedure is (copied from article):
Make sure the function is accessible to the page (i.e. declared
public), and use the MasterType declaration in the ContentPage:
<%# Page .... %>
<%# MasterType VirtualPath="~/masterpage.master" %>
In the page, use Page.Master.MyFunction() to access the function.
*Note: before being able to access the function, you'll need to save & build.
The problem is that I do not see the method. Here is what I have:
Web Page (stored in /MyFolder, so /MyFolder):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Logout.aspx.cs" Inherits="BvCorpMain.Candidates.Logout" %>
<%# MasterType VirtualPath="/SiteMasters/Site.Master" %>
Site.Master CS file (stored in /SiteMasters folder):
public void UpdateUserBlocksToCookie()
{
}
When I go into the code behind for the logout page and in a method I type in "Page.Master.", I do not see my method.

Your page is inheriting from System.Web.UI.Page, which only knows that its master page is of type System.Web.UI.MasterPage. If you are making modifications to a child class of MasterPage, then you need to cast the Page.Master property to your child class.
public class MyPage : System.Web.UI.Page
{
public new MyMaster Master { get { return base.Master as MyMaster; } }
public void Page_Load(object sender, EventArgs e)
{
Master.MyMasterPageFunction();
}
}
public class MyMaster : System.Web.UI.MasterPage
{
public void MyMasterPageFunction()
{
}
}

The previous answer did educate me, however I believe the resolution was to restart VS2012, maybe cleaning the solution and rebuilding did not hurt. Either way.
Microsoft adds in the following code automatically to the .aspx.designer.cs file.
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new MyNamespace.Site Master {
get {
return ((BvCorpMain.Site)(base.Master));
}
The previous answer conflicts with this definition. Also, the previous answer of MyMaster, although granting access does not give (automatically at least) to needed form information. I checked. Using the existing master file is the cleanest.
The definition for the master.cs file is:
namespace MyNamespace
{
public partial class Site : System.Web.UI.MasterPage
As you can see, Microsoft did give access to MyNamespace.Site, which is what I needed, with "Master.".
I did not think to check the .aspx.designer.cs file for that definition, when I was having the problems. Possibly the definition was lacking and got added later, when either I rebuilt or did a save, which I had previously done, or whatever.
Knowing the addition does simplify things, as I can add that in manually if it does not exist using that construct.

Related

Master property is not auto generated in aspx designer causing runtime errors

I have a content page that uses a MasterPageFile, and in the code we try to access a master property Master.SessionId.
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminFrontend.Master" AutoEventWireup="true"
CodeBehind="Reasons.aspx.cs" Inherits="Admin.Other.Reasons" %>
<asp:Content ID="Content2" ContentPlaceHolderID="cphMainBody" runat="server">
<reason session-id="<%=Master.SessionId%>">
</reason>
</asp:Content>
But the Master.SessionId is not recognized, Master is not referring to the correct master file. Similar code works on another file within the project. The only notable difference that we found is that the page that works has the following auto-generated code in the aspx.designer.cs file.
public partial class MyChart {
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new Admin.AdminFrontend Master {
get {
return ((Admin.AdminFrontend)(base.Master));
}
}
}
This is the designer for my Reasons.aspx file.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Admin.Other
{
public partial class Reasons
{
}
}
I am not sure what is the problem, why in one file that property is auto-generated and not in the other. I thought Visual Studio is doing something crazy. I restarted VS2019 and also tried restarting my machine. Both didn't solve the
problem.
There may not even 'be' a Designer page for the "Reasons.aspx.cs". Please check to ensure it exists for the Reasons.aspx page (open the Solution Explorer and view the associated to the Reason.aspx file). If the Designer file does not exist, select/highlight the Reason.aspx file in the Solution Explorer, then use the upper menu bar (in Visual Studio), and choose the Project > Convert to Web Application selection. If that selection is missing from the Projects pulldown menu, this typically indicates all Designer files are connected to your CodeBehind files.
If you do have a Reasons.aspx.designer.cs, please provide the code here so we can compare it to the one from your MyChart example.
At your Reasons.aspx.cs file,
you can add public property and return the Master.sessionID.
For example;
public partial class MyChart
{
public string MySession
{
get
{
return Master.SessionID;
}
}
}
At your aspx file, use
<reason session-id="<%=MySession%>"></reason>

Web site to Web App: aspx.cs can't see controls in .aspx

I am trying to convert a web site project to a web app and I'm running into some issues where the .aspx.cs files can't see any controls in the .aspx. I've tried deleting the .designer.cs files and converting to a web app again but that hasn't fixed my problems. If I change the namespace of the .designer.cs files to 'SoftwareCheckout,' (the same namespace as my .aspx.cs) the .aspx.cs can see the controls in the .aspx fine, but since the .designer.cs is auto-generated, I will loose any changes to it as soon as it's regenerated. This leads me to believe it is a problem with my namespaces but I'm not 100% sure.
Here is the top line of my .aspx called StuCheckout.aspx:
<%# Page Language="C#" AutoEventWireup="True" Inherits="StuCheckout" Codebehind="StuCheckout.aspx.cs" %>
Here's the first couple lines of my .aspx.cs called StuCheckout.aspx.cs (lblUser and lblTime can't be accessed for example)
namespace SoftwareCheckout
{
public partial class StuCheckout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblUser.Text = CurrentUser.getUsername();
lblTime.Text = CurrentUser.getDate();
setLocalRestrictions();
if (!(lblErrorText.Text == String.Empty))
lblErrorText.Visible = true;
My .designer.cs looks like this:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class StuCheckout {
/// <summary>
/// Head1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
Has anyone else ran into this issue? I'm running out of ideas here, any help is greatly appreciated!
Try adding the namespace to the Inherits and Class declarations on your front-side (.aspx) pages; the #Page directive has an Inherits or Class attribute you can use.
See "Additional Conversion Options" section here:
http://msdn.microsoft.com/en-us/library/aa983476(v=vs.100).aspx

Type '_Default' already defines a member called 'Page_Load' with the same parameter types

I've been renaming some classes and packages in my aspx project and now i have this error:
"Type '_Default' already defines a member called 'Page_Load' with the
same parameter types"
I have two aspx pages. In the default.aspx codebehind i see:
Default.aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="_Default" %>
Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
//error line under 'Page_Load'
}
search.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="search.aspx.cs" Inherits="_Default" %>
search.aspx.cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
}
Every new ASPX page I add to my project is automaticly added to some namespace.
I've tried changing the inherits attribuut. But i couldn't find a way to fix this error and to get rid of the namespace.
I'm using Visual Studio 2010.
Every page you add is automatically configured to namespace depending on your folder structure. I don't see enough code and structure, but are you sure, that you don't have the Page_Load defined twice? At least the error message says so. Does it behave same even when you use different class name than _Default ?
After edits:
Yea, there we go. You define same class (_Default) in both Default.aspx and Search.aspx ... You should rename your classes according to conventions. ie: use class "Default" in your Default.aspx and use class "Search" in your Search.aspx
Double click the error, temporarily rename the Page_Load to something else. Go down into the body of the function and type Page_Load. Press F12. That will get you to the place where you have second Page_Load method already defined. You'll probably see that it's in another partial _Default class in the same namespace.
Just to add up a specific case.
You can come across to this situation when you convert Web Site into Web Application.
When your project in form of Web Site, when you add for example Default.aspx into two different folders they both created without namespace with the same class name. Both declared partial and it is just fine. But when you convert into Web Application and try to build they start conflicting as they are in the same namespace, declared partial and have their own Page_Load methods.
One of the solutions can be giving distinct class names or encapsulating into different namespaces in accordance with the folder structure.
Since your class is public partial class _Default it's probably some naming that is causing the problem. Try to identify the other part(s) of _Default. Since it's a partial class you're able to have as many partials as you want.. Problem is probably that Page_Load is defined in one of those.
Below follows issues I have encountered when copying files into my solution, clicking on the reported error or on "Go to Definition" mislead me to spot the cause. The hint is one line above..... !
I'm exposing the Problem AND how I finally Resolved it.
Errors when building the application:
Error 1 Type 'Solution1.Web.yourABC' already defines a member
called 'Page_Load' with the same parameter types
C:\\trunk\Solution1.Web\yourABC.aspx.cs 12 24
Solution1.Web
Error 2 Type 'Solution1.Web.yourABC' already defines a member
called 'Page_Load' with the same parameter types
C:\\trunk\Solution1.Web\GuideABT.aspx.cs 12 24
Solution1.Web
How the problem arose:
I copy/pasted a file .aspx in the same solution to make a new file.
C#: Error like below started to appear; worst other misleading errors started to impact the application at runtime:
* Be aware that error 1 IS NOT an error it is CORRECT, as it is the source code
Error 1 Type 'Solution1.Web.yourABC' already defines a member called 'Page_Load' with the same parameter types C:\<folderpath>\trunk\Solution1.Web\yourABC.aspx.cs 12 24 Solution1.Web
Error 2 Type 'Solution1.Web.yourABC' already defines a member called 'Page_Load' with the same parameter types C:\<folderpath>\trunk\Solution1.Web\GuideABT.aspx.cs 12 24 Solution1.Web
Both classes "Page_Load" are empty, normally they are generated automatically by the Visual Studio Engine
Solution:
Change the .cs file of the newly create/pasted aspx page to reflect the page name after the Class "name". In this case "GuideABT.aspx" is the new pasted & renamed aspx file:
Correction on Error 1: NO CORRECTION NEEDED as it is the copied from file. MAKE SURE THAT the name of the file and the name of the class reference ARE the same in the .cs files:
File name yourABC.aspx, check the .cs extension files:
namespace Solution1.Web
{
public partial class yourABC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Correction on Error 2: MODIFY the pasted file. Correct the CLASS NAME to reflect the name of the .aspx file.
File name GuideABT.aspx, check the .cs extension files:
ORIGINAL code in .cs
namespace Solution1.Web
{
public partial class *yourABC* : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
CORRECTED this code in .cs TO
namespace Solution1.Web
{
public partial class **GuideABT** : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Issue RESOLVED.
Cheers.

Dynamically Load a user control (ascx) in a asp.net website

I am trying to dynamically load a user control in an asp.web site. However due to how asp.net websites projects are setup (I think), I am not able to access reach the type definition of the user control.
I get a message saying that my class HE_ContentTop_WebControl1 is: he type or namespace name 'HE_ContentTop_WebControl1' could not be found (are you missing a using directive or an assembly reference?)
Any idea how this could be made to work ? I have attempted using namespace but it seems to me that asp.net websites are not designed to work with namespaces by default. I would be interested in a non namespace approach.
TIA
public partial class HE_Default :
System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
var control = (HE_ContentTop_WebControl1)Page.LoadControl("~/ContentTop/WebControl1.ascx");
}
}
Assuming the control exists in the same assembly as your web project, you need to add a reference directive in your .aspx file,
e.g:
<%# Reference Control="~/Controls/WebControl1.ascx">
Keep in mind it often takes a few minutes (or sometimes a build) for IntelliSense to pick this up.
It can easily be done using namespaces. Here's an example:
WebControl1.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebControl1.ascx.cs" Inherits="MyUserControls.WebControl1" %>
Notice that Inherits references the namespace (MyUserControls), and not just the class name (WebControl1)
WebControl1.ascx.cs:
namespace MyUserControls
{
public partial class WebControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Notice that the class have been included in the namespace MyUserControls
Default.aspx.cs:
using MyUserControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var control = (WebControl1) Page.LoadControl("~/WebControl1.ascx");
}
}
This approach potentially allow you to redistribute your user controls (or keep them in a separate project) without the hassle of referencing them in your .aspx files.
Namespaces are not supported under the website model. As such, I could not get any of the solutions proposed to work. However, there is a solution. Create an interface and place it into app code and then implement the interface in the user control. You can cast to the interface and it works.
The subject of this post is a bit misleading. If you just want to add a control dynamically, you will not have to reference the control and therefore you can just add it with something simple like:
protected void Page_Load(object sender, EventArgs e)
{
Page.Controls.Add(Page.LoadControl("~/MyControl.ascx"));
}
without any namespace hassel.
the reference is not enough using
<%# Reference Control="~/Controls/WebControl1.ascx">
in the aspx file is just one part of the answer.
you need also to add the calssName in the User Control aspx file
<%# Control ClassName="WebControl1" Language="C#" AutoEventWireup="true" CodeFile="WebControl1.ascx.cs" Inherits="AnySpaceName.DateSelector" %>
and then you can use the userontrol in your aspx file
AnySpaceName.WebControl1 WC = (AnySpaceName.WebControl1)Page.LoadControl("~/WebControl1.ascx");
Casting the user control this way may create many problems .my approach is to create a class (say control Class) put all the properties and method you need for casting in it and inherit this class from System.Web.UI.UserControl .Then in your user cotrol code file instead of System.Web.UI.UserControl user this control class .
now when ever you need casting, cast with this class only . it will be light casting as well.

ASP.NET UserControl Inheritance

I have a UserControl that is working fine. It is declared like this.
public partial class DynamicList : System.Web.UI.UserControl
{
protected static BaseListController m_GenericListController = null;
public DynamicList()
{
m_GenericListController = new GenericListController(this);
}
}
Now I want to override this control so I can change some of the properties. I have created a class like this.
public partial class JobRunningList : DynamicList
{
public JobRunningList()
{
m_GenericListController = new JobListController(this);
(m_GenericListController as GenericListController).ModuleId = 14;
}
}
It appears that the controls in the DynamicList are not getting created though when I use the JobRunningList control now causing predictably bad results. The DynamicList UserControl has a ListView on it and a few other controls. It appears these are not created when using the JobRunningList. Is there any secret to this?
The boring workaround would be to make JobRunningList as plain old user control that contains a DynamicList and just sets the properties of the inner control in its OnLoad. That's awkward if DynamicList has many other properties that you want to access from the page though, as JobRunningList would have to define matching properties of its own. Getting back to the inheritance approach, then...
The DynamicList class just contains the code behind logic, so what you're doing works nicely if you want the second control to reuse the logic behind the first but provide a new UI of its own.
The markup in your .ascx file gets compiled into another class that inherits DynamicList, so if you can get your JobRunningList class to inherit that class instead of DynamicList, you'll get the result you want. This class gets a default name derived from the filename, but you can avoid guessing that by setting a ClassName in the control directive to use instead of the automatic name.
Take a simple base control like
<%# Control Language="C#" AutoEventWireup="true"
CodeFile="HelloControl.ascx.cs" Inherits="HelloControlBase"
ClassName="MyControls.HelloControl" %>
Hello <%= Name %>
with an unexciting code-behind like
public partial class HelloControlBase : System.Web.UI.UserControl
{
public string Name
{
get;
set;
}
}
Now we want to override the Name property in a new control. First we need HelloAlice.ascx
<%# Control Language="C#" AutoEventWireup="true"
CodeFile="HelloAliceControl.ascx.cs"
Inherits="HelloAliceControl" %>
Not much to see here, since we're leaving all the work to the original ascx. Now in the code-behind,
public partial class HelloAliceControl : MyControls.HelloControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.Name = "Alice";
}
}
We just inherit MyControls.HelloControl and set the Name property, and it looks like we're done.
The problem is knowing when MyControls.HelloControl is visible. As long as your derived control is in the same directory as the parent control you'll probably be OK, otherwise it's quite easy to run into build errors complaining that the class doesn't exist because the parent control hasn't been compiled yet.
If I understand correctly, you want the interface to be the same. In that case, I would create some properties instead. Perhaps just a simple enumeration i.e. ListType.

Resources