how to access master page control from content page - asp.net

I have a master page which contains a label for status messages. I need to set the status text from different .aspx pages. How can this be done from the content page?
public partial class Site : System.Web.UI.MasterPage
{
public string StatusNachricht
{
get
{
return lblStatus.Text;
}
set
{
lblStatus.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have tried this, but was unsuccessful in making it work:
public partial class DatenAendern : System.Web.UI.Page
{
var master = Master as Site;
protected void Page_Load(object sender, EventArgs e)
{
if (master != null)
{
master.setStatusLabel("");
}
}
protected void grdBenutzer_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//some code
if (master != null)
{
master.setStatusLabel("Passwort erfolgreich geändert.");
}
}
catch (Exception ex)
{
if (master != null)
{
master.setStatusLabel("Passwort konnte nicht geändert werden!");
}
}
}
}
}

In the MasterPage.cs file add the property of Label like this:
public string ErrorMessage
{
get
{
return lblMessage.Text;
}
set
{
lblMessage.Text = value;
}
}
On your aspx page, just below the Page Directive add this:
<%# Page Title="" Language="C#" MasterPageFile="Master Path Name"..... %>
<%# MasterType VirtualPath="Master Path Name" %> // Add this
And in your codebehind(aspx.cs) page you can then easily access the Label Property and set its text as required. Like this:
this.Master.ErrorMessage = "Your Error Message here";

In Content page you can access the label and set the text such as
Here 'lblStatus' is the your master page label ID
Label lblMasterStatus = (Label)Master.FindControl("lblStatus");
lblMasterStatus.Text = "Meaasage from content page";

It Works
To find master page controls on Child page
Label lbl_UserName = this.Master.FindControl("lbl_UserName") as Label;
lbl_UserName.Text = txtUsr.Text;

I have a helper method for this in my System.Web.UI.Page class
protected T FindControlFromMaster<T>(string name) where T : Control
{
MasterPage master = this.Master;
while (master != null)
{
T control = master.FindControl(name) as T;
if (control != null)
return control;
master = master.Master;
}
return null;
}
then you can access using below code.
Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null)
lblStatus.Text = "something";

You cannot use var in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}

This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.
Crucial bit: Master.Master.
See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl
Example:
'Find the content control
Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")
'now find controls inside that content
Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")

If you are trying to access an html element: this is an HTML Anchor...
My nav bar has items that are not list items (<li>) but rather html anchors (<a>)
See below: (This is the site master)
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
<a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>
Now in your code behind for another page, for mine, it's the login page...
On PageLoad() define this:
HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;
HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;
Now we have accessed the site masters controls, and have made them invisible on the login page.

Related

how to update master page in all child pages without refreshing

As i am new to asp.net i need some help from you,
i am using a MasterPage and child pages.
In master page I have a Label in which it shows the items added to cart.
when i am adding a product in products page.aspx it is updated in master page as (1 item) and showing in the label but when i am coming to homepage.aspx it is not showing i am using same master page in home.aspx.
If i refresh the home.aspx, it is updated. I need to update it without refreshing.
Sample code look like this
MasterPage markup: Here's the label in your masterpage which you want to be update from childpage
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
MasterPage.cs:
public partial class MasterPage : System.Web.UI.MasterPage
{
public string labeltext
{
get
{
return Label1.Text;
}
set
{
Label1.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
ChildPage.cs:
protected void Page_Load(object sender, EventArgs e)
{
this.Master.labeltext = "Your value"; // set your value
}

Set value to TextBox in UserControl inside placeholder

I have an textbox inside an user control. I created dinamically this user control and load in placeholder.
But when I tried to assign a value to the textbox, I raised next below error:
Object reference not set to an instance of an object
This is the user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="IVT_FormClient.ascx.cs" Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_FormClient" %>
<asp:Panel ID="pnlContainer" runat="server">
<asp:TextBox ID="txtClientNumber" runat="server"></asp:TextBox>
</asp:Panel>
The access modifier is (In the user control):
public string TxtFirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
In the web form I have the control reference:
<%# Reference Control="~/Evi/IVT/Sublayouts/IVT_FormClient.ascx" %>
In the code behind of the user control is:
public partial class frm_VerifyIdentity : System.Web.UI.Page
{
IVT_FormClient ivtFormClient = new IVT_FormClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IVT_FormClient ivtFormClient = (IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}
}
}
The error occur is this line of code:
ivtFormClient.TxtFirstName = UserClient.FirstName;
Do not create an instance of a UserControl via constructor but with LoadControl as you have already done in Page_Load. However, you are doing that only if(!IsPostBack). Hence the control is instantiated the next postback via constructor.
Also, you have to recreate dynamic controls on every postback. I would suggest to add the UserControl delaratively to the page. You can hide/show it accordingly. Otherwise you need to create/add it always, best in Page_Init instead of Page_Load.
So this is not best-practise(just add it to the page) but should work as desired:
IVT_FormClient ivtFormClient = null;
protected void Page_Init(object sender, EventArgs e)
{
ivtFormClient =(IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}

How to Add Dynamic Meta Tag to Site.Master from Database?

We have a series of meta tag values in our database that need to be passed to the Site.master depending on the site being served. How would I include the BingMetaTag database field value in my Page Load event? We need to pass the content attribute value from the database to the meta tag in the master page.
Page_Load is as follows:
public partial class Site : System.Web.UI.MasterPage {
protected DealerInformation objDealerInformation = null;
protected DealerSite objDealerSite = null;
protected ConnectionStringConfig dbConfig = null;
protected void Page_Load(object sender, EventArgs e) {
dbConfig = Session["DBConfig" + Request.Url.Host] as ConnectionStringConfig;
objDealerInformation = CommonFunctions.GetDealerInformation(dbConfig);
objDealerSite = Session["DealerSite" + Request.Url.Host] as DealerSite;
try {
imgGoogleAdServices.Src = string.Format(#"//googleads.g.doubleclick.net/pagead/viewthroughconversion/{0}/?value=0&label={1}&guid=ON&script=0;", objDealerSite.GoogleConversionID, objDealerSite.GoogleConversionLabelRemarketing);
} catch {
imgGoogleAdServices.Src = "";
}
try {
WebEntitiesModel context = new WebEntitiesModel(dbConfig["WebConnection"]);
String aspPage = HttpContext.Current.Request.Url.AbsolutePath.ToString().ToLower();
MetaTag pageMetaTag = (from m in context.MetaTags
where m.Page == aspPage
select m).Single();
Page.Title = (pageMetaTag.PageTitle != null ? pageMetaTag.PageTitle : "");
Page.MetaKeywords = (pageMetaTag.MetaKeywords != null ? pageMetaTag.MetaKeywords : "");
Page.MetaDescription = (pageMetaTag.MetaDescription != null ? pageMetaTag.MetaDescription : "");
} catch {
Page.Title = "";
Page.MetaKeywords = "";
Page.MetaDescription = "";
}
Note that we are already bringing in title, meta keywords and meta description from another database table. We just need to add the value of BingMetaTag as a separate meta tag entry.
It sounds like you're using WebForms rather than MVC, which actually makes this a bit easier.
In your Site.master file:
<head>
<meta id="someMeta" runat="server" name="something" value="" />
</head>
In your Site.master.cs file's class:
protected HtmlGenericControl someMeta;
public String SomeMetaValue {
get { return this.someMeta.Attributes["value"]; }
set { this.someMeta.Attributes["value"] = value; }
}
In your page's class
public void Page_Load(Object sender, EventArgs e) {
SiteMaster master = (SiteMaster)this.Master;
master.SomeMetaValue = "someValueFromDatabase";
}
If you have multiple types of Master pages in your project then this code will fail, so add appropriate guards and checks as needed.

How to dynamically set the Title of SiteMap from MasterPage?

In My Web.sitemap I have the following:
<siteMapNode url="~/Groups/ViewGroups.aspx" urlRoute="groups/{PostId}/{PostTitle}" />
</siteMapNode>
In my MasterPage I have implemented the ItemDataBound event to try and set the title of each page that implements the master page dynamically but for some reason the title is not being set.
protected void SiteMapPath1_ItemDataBound(object sender, SiteMapNodeItemEventArgs e)
{
string CurrentNodeTitle = GetTitleFromDatabase();
if (e.Item.ItemType == SiteMapNodeItemType.Current) {
e.Item.SiteMapNode.Title = CurrentNodeTitle;
}
}
I also tried this in the ItemCreated event but still it did NOT work.
If I set the title in the Web.sitemap then it works perfectly but when I set it using e.Item.SiteMapNode.Title = CurrentNodeTitle; the title is nto being set.
Try this.
private string currentKey = SiteMap.CurrentNode.Key
protected void SiteMapPath1_ItemDataBound(object sender, MenuEventArgs e)
{
string CurrentNodeTitle = GetTitleFromDatabase();
if (e.Item.DataPath == currentKey){
e.Item.Text = CurrentNodeTitle;
}
}
Edit note:
it should be MenuEventArgs
This question is about 6 years old now, and the one answer is completely wrong and should probably be deleted. I had a hard time finding the answer - it's not nearly as straight forward as I would have expected it to be, but the answer is pretty simple nonetheless.
Using the static SiteMap classes SiteMapResolve event from the System.Web namespace (NOT your instance of SiteMapPath!) you can manipulate the URL and Title on the fly.
In my case, I have a custom localization method that retrieves the localized strings from a database. The sitemap title's contain the key used to identify the string. This is the code behind for my Master Page:
protected void Page_Load(object sender, EventArgs e)
{
// ...
SiteMap.SiteMapResolve += (o, args) =>
{
if (SiteMap.CurrentNode == null)
return null;
SiteMapNode currentNode = SiteMap.CurrentNode.Clone(true);
currentNode.Title = SessionObject.LocalizeText(currentNode.Title);
SiteMapNode tempNode = currentNode;
while (tempNode.ParentNode != null)
{
tempNode = tempNode.ParentNode;
tempNode.Title = SessionObject.LocalizeText(tempNode.Title);
}
return currentNode;
};
// ...
}
Then in your Master Page ASPX (or presumably any ASPX page that utilizes this Master Page), you can add <asp:SiteMapPath runat="server" ... /> and it should be processed by the SiteMapResolve event.

post data using get (not post) method

I have a Webform with masterpage(where the form tag is). Inside the content page I have a textbox and a submit button. I want to send the data to the next page using GET not POST. How can I do this?
If it can apply to all pages:
<form method="get" ... >
<!-- content here -->
</form>
If you want only for a single, simple page:
protected void Submit_Click(object sender, EventArgs e)
{
string url = "NextPage.aspx?";
url = url + "&MyTxt1=" + MyTxt1.Text;
url = url + "&MyTxt2=" + MyTxt2.Text;
url = url + "&MyTxt3=" + MyTxt3.Text;
// etc.
Response.Redirect(url);
}
If you want to control the method from the content page:
// on the master page
public class SiteMaster : System.Web.UI.MasterPage
{
// replace form1 with the id of your form control
// make sure the form tag has runat="server"
public string Method
{
get { return form1.Method; }
set { form1.Method = value; }
}
// ...
}
// on the content page
protected void Page_Load(object sender, EventArgs e)
{
// replace SiteMaster with class type of the master class
((SiteMaster)this.Master).Method = "get";
}

Resources