Inside my ASP.NET application all my web content pages are derived from a base class which is derived from System.Web.UI.Page. Inside this base class I need to get some controls found in one derived class, SamplePage.aspx : BaseClass.cs. It I add the C# code below on Page Load inside SamplePage.aspx it finds the ContentPlaceHolderControl,
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder> /* defined in the master page */
/* inside SamplePage.aspx */
<ajaxtoolkit:tabcontainer runat="server" id="tabsmain" height="405px" Width="625px">
ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
AjaxControlToolkit.TabContainer container = (AjaxControlToolkit.TabContainer)cph.FindControl("tabsmain");
whereas if I add it inside the base class I get this error:
Content controls have to be top-level controls in a content page or a nested master page that references a master page.
Is there a way I can get the ContentPlaceHolder inside my base class too? And how can I access it?
Here is complete sample code how you can access ContentPlaceHolder:
First master code (Site1.master):
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebTesterInherit.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Now custom class that inherits from Page:
public class MyPage: System.Web.UI.Page
{
public System.Web.UI.WebControls.ContentPlaceHolder GetMyContentPlaceHolder()
{
System.Web.UI.WebControls.ContentPlaceHolder holder = null;
Site1 site = this.Master as Site1;
if (site != null)
{
holder = site.FindControl("ContentPlaceHolder1") as System.Web.UI.WebControls.ContentPlaceHolder;
}
return holder;
}
}
And finally page that inherits from MyPage (Default.aspx):
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTesterInherit.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click"/><br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</asp:Content>
Code for Default.aspx:
public partial class Default : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
try
{
System.Web.UI.WebControls.ContentPlaceHolder holder = base.GetMyContentPlaceHolder();
lblMessage.Text = string.Format("Holder contains {0} control(s).", holder.Controls.Count);
}
catch (Exception ex)
{
lblMessage.Text = string.Format("Error: {0}", ex.Message);
}
}
}
I've checked and you can find a control nested in ContentPlaceHolder from base class OnLoad method.
Sure it can be done... but remember that some pages may have different controls in theirs CPH. Are you sure that you are in the context of a page which actually has tabsmain control?
I think if you have to do such things you have some design problem. A mix of master page and downward FindControl (base class -> derived class) just doesn't feel right.
Universal "search by id and type" method:
protected T GetControlOfType<T>(Control root, string id) where T : Control {
var stack = new Stack<Control>();
stack.Push(root);
while (stack.Count > 0) {
var control = stack.Pop();
var typedControl = control as T;
if (typedControl != null && string.Compare(id, typedControl.ID, StringComparison.Ordinal) == 0) {
return typedControl;
}
foreach (Control child in control.Controls) {
stack.Push(child);
}
}
return default(T);
}
Usage:
var control = GetControlOfType<MyControl>(Page, "MyControlServerID");
Related
I can fetch MasterPage control value in Content Page
but I can't understand how to fetch MasterPage control value in Content Page in static webmethod
on google, I found many interesting articles but all of them use ajax and jquery technology
but ajax and jquery is not suitable for me in this case
any suggestions, please?
my code below
masterpage
public partial class MasterPage : MasterPage
{
public string UserNamePropertyOnMasterPage
{
get
{
// Get value of control on master page
return lblUserName.Text;
}
set
{
// Set new value for control on master page
lblUserName.Text = value;
}
}
}
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<span style="font-size: 25px; background-color: greenyellow">
<asp:Label ID="lblUserName" runat="server" Text="Shazam"></asp:Label>
</span>
</form>
code-behind of Default.aspx.cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblCurrentUserName.Font.Size = 20;
lblCurrentUserName.BackColor = Color.Yellow;
lblCurrentUserName.Text = "Value Received in Content Page : " + Master.UserNamePropertyOnMasterPage;
}
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void SetLabel(string UserNamePropertyOnMasterPage)
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Label Hname = (Label)Master.UserNamePropertyOnMasterPage;
lblCurrentUserName.Text = Hname;
}
}
markup of Default.aspx
<%# Page Title="" Language="C#" MasterPageFile="MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# MasterType VirtualPath="MasterPage.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="lblCurrentUserName" runat="server" Text=""></asp:Label>
</asp:Content>
It is not possible to call a master page method from a static web method. This is a fundamental concept to understand in C#. Basically the master page does not exist during the web request. Only the web method is called.
Use JavaScript/jQuery to update the current page HTML.
I have this URL (mydomain.com/mypage.aspx). I want to get the file name "mypage" only in a webmethod. I tried the following code but I only get the name of the function itself (MyMethod). I don't get the name of the page from the URL. Any help is well appreciated.
EDIT
To be more specific the webmethod resides in a user control so using FilePath OR PhysicalPath would give me the name of the UserControl file name (MyUserControl) and not the aspx page (mypage) in the URL.
mypage.aspx
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<uc:myUserControl runat="server" />
</asp:content>
myUserControl.cs
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
Convert.ToString(HttpContext.Current.Request.Url)));
} }
OR
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
HttpContext.Current.Request.RawUrl));
} }
OR
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
HttpContext.Current.Request.PhysicalPath));
} }
[WebMethod]
public static string MyMethod()
{
StringBuilder SBstring = new StringBuilder();
SBstring.Append(PageName);
return SBstring.ToString();
}
Just use FilePath like this:
var fi = new FileInfo(HttpContext.Current.Request.FilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fi.Name);
Complete working solution for required structure (Master Page -> Content Page -> User Control
Site Master
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebTester.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Webform1.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebTester.WebForm1" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</asp:Content>
Webform1.aspx.cs:
namespace WebTester
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ProcessIT(string name, string address)
{
return WebUserControl1.ProcessIT(name, address);
}
}
}
WebUserControl1.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebTester.WebUserControl1" %>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something is wrong.');
}
}
</script>
<div>
<p>Please enter data:</p>
Name<br />
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
Address<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
WebUserControl1.ascx.cs:
namespace WebTester
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public static string ProcessIT(string name, string address)
{
var fi = new FileInfo(HttpContext.Current.Request.FilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fi.Name);
string result = string.Format("Name '{0}' and address '{1}' came from Page '{2}'", name, address, fileNameWithoutExtension);
return result;
}
}
}
I have a simple ASPX page that inherits from MasterPage:
(Popup.master)
<div class="text_container">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
(Privacy.aspx)
Privacy
<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
I need to add a HTML content inside the Privacy.aspx.cs:
public partial class Privacy : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
ContentPlaceHolder body = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
I saw this example but as I see I need asp control inside.
How to add just HTML content to ContentPlaceHolder1?
A ContentPlaceHolder is intended to give you the ability to add controls in your page markup with a Content control and have them appear within the context of your master page. Given that, in Privacy.aspx you can add a generic html control in BodyContent Content Control and set the InnerContent property on the added control within your code behind.
Markup
<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<span id="SpanContent" runat="server"></span>
</asp:Content>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SpanContent.InnerHtml = "<b>Hello!</b>";
}
I've got a upload function that pops up in a diffrent window, when i've submitted i want to send infomation back to the page that the upload window opened from.
Is that possible some way with ASP.net or C#?
Or would i have to use some javascript ? and how?
My 2 pages:
news.aspx - Contains a formview with my news. and a form with some inputs in.
This is where the link to open the upload page is...
uploader.aspx - Contains my upload controller and C# code to upload.
This should send a string from my C# code back to news.aspx and put it in one of my input fields or a label, not important.
uploader.aspx file:
<form id="form1" runat="server">
<div>
Vælg en fil at uploade:<br />
<asp:FileUpLoad id="FileUpLoad1" runat="server" />
<asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px" />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Behind Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class admin_Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadBtn_Click(object sender, EventArgs e) {
Label1.Text = "Status: Uploader...";
if (FileUpLoad1.HasFile) {
FileUpLoad1.SaveAs(#"C:\Users\138409\Documents\Visual Studio 2010\Projects\Musicon\img\news\" + FileUpLoad1.FileName);
Label1.Text = "Status: " + FileUpLoad1.FileName + " er blevet uploadet";
} else {
Label1.Text = "Status: Filen blev ikke uploadet...";
}
}
}
Here is some Javascript code to create a popup window and, before the popup window closes, retrieve some information. (I will add a jQuery example in a bit)
//Site1.Master
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="PopupRedirect.Site1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
//Page1.aspx
<%# Page Title="" Language="C#" MasterPageFile="Site1.Master" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="PopupRedirect.Page1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
var message = "Hello World!";
var closeWindow = function(event) {
event.preventDefault();
window.close();
};
window.onload = function() {
document.getElementById('upload').addEventListener('click', closeWindow, false);
};
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<button id="upload">Upload File</button>
</asp:Content>
//UploadPage.aspx
<%# Page Title="" Language="C#" MasterPageFile="Site1.Master" AutoEventWireup="true" CodeBehind="UploadPage.aspx.cs" Inherits="PopupRedirect.UploadPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
var popupWindow;
var windowOptions = "menubar=yes,location=yes,resizable=no,scrollbars=no,status=yes,width=350,height=350";
var upload = function (event) {
event.preventDefault();
popupWindow = window.open("Page1.aspx", "Upload Page", windowOptions);
popupWindow.onbeforeunload = pageClose;
};
var pageLoad = function(event) {
document.getElementById('uploadLink').addEventListener('click', upload, false);
};
var pageClose = function (event) {
//put the code here that you want to execute when the window is done.
//like getting the value of some javascript variables
if(typeof (popupWindow.message) != "undefined") {
alert(popupWindow.message);
}
};
window.onload = pageLoad;
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<span>Welcome to this page! Click to upload.</span>
<button id="uploadLink">Upload</button>
</asp:Content>
I have a master page which contains a usercontrol.
Now Abc.aspx is the child page of that master page.Now, child page has also a user control.
My requirement is to grab master page's user control form child page's user control.
Master Page aspx
<%# Master Language="C#" MasterPageFile="~/masterhome.Master" AutoEventWireup="true" CodeBehind="lmsmasternew.master.cs" Inherits="e2aPortal.LMS.lmsmasternew" %>
<%# Register Src="~/homeUserControl/UserProfilePic.ascx" TagPrefix="uc1" TagName="UserProfilePic" %>
<%# Register Src="~/homeUserControl/MuduleListLeftPanel.ascx" TagPrefix="uc1" TagName="MuduleListLeftPanel" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<title></title>
<script src='<%# ResolveUrl("~/Scripts/jquery-1.4.1-vsdoc.js") %>' type="text/javascript"></script>
<script src='<%# ResolveUrl("~/Scripts/jquery-1.11.1.min.js") %>'></script>
<link href='<%# ResolveUrl("~/StyleSheet/profilesidebar.css") %>' rel="stylesheet" />
<link href='<%# ResolveUrl("~/StyleSheet/font-awesome.css") %>' rel="stylesheet" />
<link href='<%# ResolveUrl("~/Content/bootstrap.min.css") %>' rel="stylesheet" />
<script type="text/javascript">
function openpage(pagename) {
$("#maincontent").load(pagename + ".aspx #maincontent", function () {
// make content visible with effect
});
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="form-group">
<div class="row" style="margin-top: 5%;">
<div class="col-xs-3">
<uc1:UserProfilePic runat="server" ID="UserProfilePic" />
<asp:Label runat="server" ID="lbl1"></asp:Label>
<br />
<uc1:MuduleListLeftPanel runat="server" ID="MuduleListLeftPanel" />
</div>
<div class="col-xs-9">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</div>
</div>
</asp:Content>
User control aspx (Used in Master page)
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MuduleListLeftPanel.ascx.cs" Inherits="e2aPortal.homeUserControl.MuduleListLeftPanel" %>
Now child page that inherits that master page
<%# Page Title="" Language="C#" MasterPageFile="~/LMS/lmsmasternew.master" AutoEventWireup="true" CodeBehind="CreateQuestionTemplate.aspx.cs" Inherits="e2aPortal.LMS.CreateQuestionTemplate" %>
<%# Register Src="~/LMS/UserControl/CreateTemplate.ascx" TagPrefix="uc1" TagName="CreateTemplate" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<uc1:CreateTemplate runat="server" ID="CreateTemplate" />
</asp:Content>
Now child page's user control
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CreateTemplate.ascx.cs" Inherits="e2aPortal.LMS.UserControl.CreateTemplate" %>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
Now child page's user control codebehind
protected void Page_Load(object sender, EventArgs e)
{
MuduleListLeftPanel control = Page.Master.FindControl("MuduleListLeftPanel") as MuduleListLeftPanel;
//Label control1 = Page.Master.FindControl("lbl1") as Label;
if (control != null)
{
control.Visible = false; // will not going to execute :D
}
}
My requirement is to hide MasterPage's usercontrol for this specific page.
Update:
Got my solution. Thanks for This Post
Problem facing
MuduleListLeftPanel muduleListLeftPanel = this.Master.LeftPanel;
UserProfilePic userProfile = this.Master.UserProfile;
muduleListLeftPanel.Visible = false; // hide sucessfully
userProfile.Attributes["style"] = "display:none"; // non working .. I need to use display none.. for both user control
First, use FindControl on the Master Page to locate the User Control (with ID UserControlOnMaster). So somewhere in the User Control located on a Page, use this code.
WebUserControl1 control = Page.Master.FindControl("UserControlOnMaster") as WebUserControl1;
When found you can then access the other Controls in that User Control.
Label LabelOnMaster = control.FindControl("Label1") as Label;
LabelOnMaster.Text = "Control found!";
Since the UserControl is protected in the parent you need to have a public function to update the control and access it from the child.
Example, in the master page:
public partial class SiteMaster : System.Web.UI.MasterPage
{
public void SetMyUserControlVisibility(bool visible)
{
MyUserControl.Visible= visible;
}
}
Now simply in the child page:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SiteMaster masterPage = (SiteMaster)this.Page.Master;
// update master page's user control here
masterPage.SetMyUserControlVisibility(true);
}
}
}