MasterPage Access Controls - c#

I have 2 master page in my web site.
MainMaster
SubMaster (Master Page:MainMaster)
Page (Master Page:SubMaster)
I have hidden fields on SubMasterPage. And i'm proccessing datas and setting hidden field value on SubMasterPage Init event. I want to get hiddenfield's value from Page.aspx
I'm trying this on Page.aspx, getting "Object reference not set to an instance of an object." error
((HiddenField)this.Master.FindControl("hiddenId")).Value
But when i have 1 master page this code works normally.
Have i a solution in this problem? Or should i try transfer datas via session/querystring e.t.c.?

You could add a property to your sub master page to return the value, and use this in the child page.
eg.
Sub Master Page
public string HiddenValue
{
get
{
//return the value of your hidden field
return HiddenID.Value;
}
}
Child page:
//Method to get the hidden value from the master page, if the master page is a sub master page
private string GetHiddenValue()
{
if (this.Master is SubMasterPage)
{
string value = (this.Master as SubMasterPage).HiddenValue;
return value;
}
else
{
return string.Empty;
}
}
if you want to go one step further you could add an extension method to the MasterPage class to call it easily from any page.
eg:
public static class MasterPageExtensions
{
public static string GetHiddenFieldValue(this MasterPage master)
{
if (master is SubMasterPage)
return (master as SubMasterPage).HiddenFieldValue;
else
return string.Empty;
}
}
public class SubMasterPage : MasterPage
{
private HiddenField _hiddenField;
public string HiddenFieldValue
{
get
{
return _hiddenField.Value;
}
}
}
public class ChildPage : Page
{
void TestMethod()
{
string hiddenValue = this.Master.GetHiddenFieldValue();
}
}
this is particularly useful when for example you have a single modal popup message box on the master page, and you want to show it from any child page.

Related

How to set public bool value in C# code behind, read in .ascx User Control?

I want to slightly modify a user control that is being loaded by various .aspx pages.
If I set a bool value in the .aspx.cs page
public bool showTemplateBGOption;
public bool TemplateBGOption
{
set { showTemplateBGOption = false; }
}
How can I read the bool value showTemplateBGOption in the .ascx control that is rendered on the same .aspx page?
You could cast the Page property to the right type, the page property needs a getter.
(somewhere in your ascx codebehind):
MyPageType page = this.Page as MyPageType;
if(page != null)
{
bool templateBGOption = page.TemplateBGOption;
}
But in this way you are hard-wiring the page with the UserControl. Instead the page should specify the TemplateBGOption to the UserControl.
(somewhere in your page's codebehind):
this.UserControl1.TemplateBGOption = this.TemplateBGOption;
You can inplement an Interface to All Pages that will use this property and then use it in the user control and in this way you can decouple a user control from a specific page but you do it to a "contract"
interface ITemplateBOption
{
bool TemplateBGOption{get;set;}
}
Public MyPage : Page, ITemplateBOption
{
public bool TemplateBGOption
{
get{...}
set{...}
}
}
In your User Control use like this:
ITemplateBOption page = this.Page as ITemplateBOption;
if(page != null)
{
bool templateBGOption = page.TemplateBGOption;
}else
{
//do something, thrown an exception for example.
}

Using values from one aspx.cs file to another aspx.cs file with a common class

common class file common.cs: This file, I have added by clicking add->new items-> class
public class common
{
public int v,n;
public int da()
{
return n= v;
}
}
Another file: It's an webpage file name is a1.aspx.cs:
common c = new common();
c.v = Convert.ToInt32(TextBox1.Text);
c.da();
Response.Redirect("ulogin.aspx");
the value from a text box stores in c.v variable
So, now, I want the value which was given in the textbox1.text in another webpage file named as ulogin.aspx.cs
I used this code:
common d=new common();
d.da();
Label1.Text = Convert.ToString(d.n);
but after running it shows the value as 0.....
In a web application, you'll need to persist the information somewhere common (typically Session for per user info or Application for per application info) so that it can be used between different pages & user controls in your application.
I'd suggest adding a Session backed property to your page & usercontrol which accesses a common Session["variable"]. Something like the following.
(i.e. lets imagine your code was being exectued on a button click)
a1.aspx.cs
public int ValueToStore
{
get
{
return Session["ValueToStore"] != null
? (int)Session["ValueToStore"]
: 0
}
set
{
Session["ValueToStore"] = value;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ValueToStore = Convert.ToInt32(TextBox1.Text);
Response.Redirect("ulogin.aspx");
}
ulogin.aspx.cs
public int ValueToStore
{
get
{
return Session["ValueToStore"] != null
? (int)Session["ValueToStore"]
: 0
}
set
{
Session["ValueToStore"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = ValueToStore.ToString();
}
As you can see, you now have some code duplication between the two pages, so the next step would be to consider implementing a basepage which as the common property, and then inherit that from a1.aspx & ulogin.aspx.
i.e.
public class a1 : BasePage
{
...
}
public class ulogin : BasePage
{
...
}
public class BasePage : System.Web.Page
{
//Put ValueToStore property here.
}
There are many users visiting same page, they may set different value, and the expected result is whatever value is set by an user on Page 1 need to be displayed in Page 2.
Any Web technology is stateless as they use HTTP which is stateless again.
However there are many ways to get this done, each method has their own advantages.
--Session--
Please use session variable to store your value, which is a kind of variable.
Each user has different session variable to store, and its available
Until the user logs out (i.e. till Session is available)
Storage: Server Memory
public class Common
{
public int? Data
{
get
{
if(Session["Data"]!=null)
{
return int.Parse(Session["Data"].ToString());
}
return null.
}
set
{
Session["Data"]=value;
}
}
}
--Query String--
You can pass value from one page to another page using query string.
Page 1
int value=1;
Response.Redirect("Page2.aspx?data="+value.ToString())
Page 2
if(!string.IsNullOrEmpty(Request["data"]))
{
int value=int.Parse(Request["data"]);
}
--Posting--
You can also post the value from one page to another page.
Page 1 (html)
<form action="page2.aspx" method="post">
<input type="hidden" name="data" value="1"/>
</form>
Page 2
if(!string.IsNullOrEmpty(Request["data"]))
{
int value=int.Parse(Request["data"]);
}
There are even more ways... You have to select what is suitable for your scenario.
Read ASP.NET State management
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
If the page ulogin.aspx is designed to be always redirected from a1.aspx, then set the PreviousPageType in ulogin.aspx and get the previous page values by this.PreviousPage instance. (Cross-Page-PostBack)
Convert member v to a property of common. Store common into a Session variable. And once you are ready to get the value, cast session variable to common and access v property from there.

UserControl pass Value to MasterPage Content

I am coding in a userControl,
how can I pass text to a control I placed in one of the contents?
It's a literal by the way
Thank you
Create a public property in Master page.
public string WhateverPropertyName
{
get
{
return LiteralControlInMasterPage.Text;
}
set
{
LiteralControlInMasterPage.Text = value;
}
}
and then access it from the usercontrol as
Page.Master.WhateverPropertyName = "Whatever new value";
If you cannot access/update master page use
Literal mpLiteral = (Literal) Master.FindControl("masterPageLiteralControlID");

Access Master Page public method from user control/class/page

I am to access a method on my master page. I have an error label which I want to update based on error messages I get from my site.
public string ErrorText
{
get { return this.infoLabel.Text; }
set { this.infoLabel.Text = value; }
}
How can I access this from my user control or classes that I set up?
To access the masterpage:
this.Page.Master
then you might need to cast to the actual type of the master page so that you could get the ErrorText property or make your master page implement an interface containing this property.
Page should contain next markup:
<%# MasterType VirtualPath="~/Site.master" %>
then Page.Master will have not a type of MasterPage but your master page's type, i.e.:
public partial class MySiteMaster : MasterPage
{
public string ErrorText { get; set; }
}
Page code-behind:
this.Master.ErrorText = ...;
Another way:
public interface IMyMasterPage
{
string ErrorText { get; set; }
}
(put it to App_Code or better - into class library)
public partial class MySiteMaster : MasterPage, IMyMasterPage { }
Usage:
((IMyMasterPage )this.Page.Master).ErrorText = ...;

Passing User Control Class to Host Page

How can I pass user control properties to the page AND make these properties available to all methods on the page (and not just to one method that is fired on a control action, e.g. onControlClick)
I have a set up of essentially 3 pages:
user control (ascx/cs)
class (cs) - that contains user control properties
host page (aspx/cs) - references the user control
The user control consists of 3 interrelated dropdowns. I'm having success passing these dropdown values through a class onto the page via an event that is fired when a user clicks on the dropdown menu. So this way the host page is continously aware of the values in the user control. However, I want the page to use the control's properties (stored in a class) on all of its methods - how do I make this user control class available to all?
Also I'm using ASP.NET and C# by the way.
Here's the Code (not sharing the full code here - just the snippets of a similar code block)
On the ASPX for Menu Host Page:
<linked:LinkMenu2 id="Menu1" runat="server" OnLinkClicked="LinkClicked" />
Host Page (cs):
protected void dropdownclicked(object sender, ddtestEventArgs e)
{
if (e.Url == "Menu2Host.aspx?product=Furniture")
{
lblClick.Text = "This link is not allowed.";
e.Cancel = true;
}
else
{
// Allow the redirect, and don't make any changes to the URL.
}
}
Host Page (aspx)
<asp:dropdowncustom ID="dddone" runat="server" OnddAppClicked="dropdownclicked" />
Control (cs)
public partial class usercontrol_tests_dropdown1 : System.Web.UI.UserControl
{
public event ddtestEventHandler ddAppClicked;
}
public void selectapp_SelectedIndexChanged(object sender, EventArgs e)
{
ddtestEventArgs args = new ddtestEventArgs(selectlink.SelectedValue);
ddAppClicked(this, args);
}
Class:
public class ddtestEventArgs : EventArgs
{
// Link
private string link;
public string Link
{
get { return link; }
set { link = value; }
}
public ddtestEventArgs(string link)
{
Link = link;
}
}
public delegate void ddtestEventHandler(object sender, ddtestEventArgs e);
Hopefully this is what you're after. The best way to do it is to expose your controls as public properties from your user control. So, in your user control, for each drop down list add a property:
public DropDownList DropDown1
{
get { return dropDownList1; }
}
public DropDownList DropDown2
{
get { return dropDownList2; }
}
You can do the same for any other properties you want to access on the host page:
public string DropDown1SelectedValue
{
get { return dropDownList1.SelectedValue; }
set { dropDownList1.SelectedValue = value; }
}
Then, from your host page you can access the properties through the user control:
string value = UserControl1.DropDown1SelectedValue;
or
string value = UserControl1.DropDownList1.SelectedValue;
Here's a couple of other answered questions that you might find useful as I think (if I've understood correctly) this is what you're doing:
Getting data from child controls loaded programmatically
How to change the value of a control in a MasterPage.

Categories

Resources