Accessing Code Behind for a Control in a Master Page - c#

I need to display a control consistently across a set of pages. So I'm using a MasterPage to do that in ASP.NET/C#. However I also need to programmatically access this control, mostly provide options to view/hide depending on whether the controls checkbox is clicked.
Here is the Source for the MasterPage
<div id="verifyInitial" runat="server">
<asp:CheckBox ID="chkInitialVerify" runat="server"
oncheckedchanged="chkInitialVerify_CheckedChanged" />
I agree that my initial data is correct.
</div>
<div id="verifyContinuous" runat="server">
<asp:CheckBox ID="chkContinuousVerify" runat="server"
oncheckedchanged="chkContinuousVerify_CheckedChanged" />
I agree that my continuous data is correct
</div>
Now in the code behind I want to perform the following operations. Basically if a person clicks on the checkbox for the initial div box, then the initial box disappears and the continous box shows up. However it seems that the code behind for the MasterPage does not activate whenver I click on the checkbox. Is that just the way MasterPages are designed? I always thought you could do add some sort of control functionality beyond utilizing the Page Load on the Master Page.
protected void chkInitialVerify_CheckedChanged(object sender, EventArgs e)
{
verifyContinuous.Visible = true;
verifyInitial.Visible = false;
}
protected void chkContinuousVerify_CheckedChanged(object sender, EventArgs e)
{
verifyContinuous.Visible = false;
}

If you're expecting the two controls to trigger a change for that page immediately then you'll need to set the AutoPostBack property to true for both of them:
<div id="verifyInitial" runat="server">
<asp:CheckBox ID="chkInitialVerify" runat="server" oncheckedchanged="chkInitialVerify_CheckedChanged" AutoPostBack="true" />
I agree that my initial data is correct.
</div>
<div id="verifyContinuous" runat="server">
<asp:CheckBox ID="chkContinuousVerify" runat="server" oncheckedchanged="chkContinuousVerify_CheckedChanged" AutoPostBack="true" />
I agree that my continuous data is correct
</div>
Otherwise, you need an <asp:button /> or some other control on the page to trigger a postback and cause your event handlers to run. The button, or other control, can either be on your masterpage or on your content page, the choice is entirely yours.

Related

checkbox event not firing when checkbox is checked and it works for uncheck checkbox

<asp:PlaceHolder runat="server" ID="phShowMonsterSourceFacet" EnableViewState="true">
<div class="oneSearchFilter">
<div>
<div class="filterItem chkMonsJobs">
<asp:CheckBox ID="chkMonsJobs" runat="server" AutoPostBack="true" Checked="true" EnableViewState="true" ViewStateMode="Enabled" OnCheckedChanged="ChkMonsJobs_CheckedChanged" CssClass="MNSColumnTextViewMore" />
</div>
</div>
</div>
</asp:PlaceHolder>
public event EventHandler RefineSearchtrivoxMonsJobCheckBoxChecked;
protected void ChkMonsJobs_CheckedChanged(object sender, EventArgs e)
{
if (RefineSearchtrivoxMonsJobCheckBoxChecked != null)
{
RefineSearchtrivoxMonsJobCheckBoxChecked(this, EventArgs.Empty);
}
}
check box event is triggered only when check box is unchecked the other way is not working..
In order to get the behavior that you report, I had to set :
EnableViewState="false"
at the page level (or on a container of the CheckBox). If you set:
EnableViewState="true"
everywhere, it works for both check and uncheck actions.
An even simpler solution is to remove all EnableViewState and ViewStateMode attributes from your markup and use the default values.
UPDATE
If you want to disable the ViewState at the page level and enable it for individual controls, you can set this at the page level:
ViewStateMode="Disabled"
And this for each control that needs the ViewState:
ViewStateMode="Enabled"
In that case, you should not use EnableViewState in the markup, since using both attributes can make things more confusing...

Getting data back from a dynamically created control within an asp:panel

I'm currently trying to create a web based wizard tool. I have a Wizard page that contains navigation buttons and an asp panel that will contain the individual wizard panels.
<asp:Panel ID="wizardControlPanel" runat="server">
<!-- Wizard panel goes here -->
</asp:Panel>
<asp:Button ID="backButton" runat="server" Text="< Back" OnClick="BackButton_Click" />
<asp:Button ID="nextButton" runat="server" Text="Next >" OnClick="NextButton_Click" />
<asp:Button ID="cancelButton" runat="server" Text="Cancel" PostBackUrl="~/"/>
One control dynamically fills a checkboxlist
<asp:Label ID="Title" runat="server" Text=""></asp:Label>
<asp:Label ID="DescriptionLabel" runat="server" Text ="Description for the wizard"></asp:Label>
<asp:CheckBoxList ID="ProjectSelector" runat="server" DataTextField="ProjectName" DataValueField="Id" ></asp:CheckBoxList>
I dynamically load this control into my wizardControlPanel once the checkbox is populated.
WizardControl = (BaseWizardControl)LoadControl(("~/Views/" + e.ControlType.Name + ".ascx"));
wizardControlPanel.Controls.Add(WizardControl);
The problem is; on postback I then need to be able to find out which checkboxes were checked server side, but the control no longer exists.
I can't find it on the _page variable. Running in to problems (I think) because I am adding the control to a content holder. How can I get this control back?
It is there, you just won't be able to access it using an ID. You'll need to find it by looking through the wizardControlPanel.Controls collection. I think there is a property that represents the filename you used. But it would be best to use the debugger to track down either where it is in the collection or an identifier you can use to find it.
Having done this once or twice, I think I also remember that you'll need to recreate the control prior to the OnLoad event of the life cycle so that the postback will be able to populate it.
As Markus says, there is probably a better way to do what you are trying to do. But if you MUST load this dynamically, this is how you should go about locating it.
If you add controls dynamically in ASP.NET WebForms, you need to re-add them manually very early in the page lifecycle of the PostBack (e.g. by overriding OnInit and creating the control with the same id in this code) in order to be able to retrieve the values. See this link for a How-To.
The following sample shows the basic steps. It consists of an ASPX-page that contains a Panel as a placeholder:
<asp:Panel ID="wizardPanel" runat="server">
</asp:Panel>
<asp:Button ID="btn" runat="server" Text="Do a postback" />
<br />
<asp:Label ID="lbl" runat="server" />
This is the codebehind-file:
public partial class DynamicUserControls : System.Web.UI.Page
{
protected UserControl userCtrl;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page.IsPostBack)
CreateUserControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
CreateUserControl();
else
{
lbl.Text = "The following values were selected: " + string.Join(", ", ((IGetSelectedValues)userCtrl).SelectedValues);
}
}
private void CreateUserControl()
{
if (Request["UserCtrl"] == "A")
{
userCtrl = (UserControl) LoadControl("~/MyUserControlA.ascx");
userCtrl.ID = "myUserCtrl";
wizardPanel.Controls.Add(userCtrl);
}
else if (Request["UserCtrl"] == "B")
{
userCtrl = (UserControl)LoadControl("~/MyUserControlB.ascx");
userCtrl.ID = "myUserCtrl";
wizardPanel.Controls.Add(userCtrl);
}
}
}
The basic steps are the following:
The page determines the user control type to be created upon a Request parameter during Page_Load (or later if necessary). It assigns the ID myUserCtrl to the UserControl.
Upon a PostBack, the page inspects the Request parameters again and re-creates the UserControl with the same ID myUserCtrl. This is important so that ASP.NET can retrieve the new values of the control from the postback data after the page initialization phase. The hardest part is usually to decide which user controls to create, because the data that are available in OnInit is usually not too many.
In Page_Load, the user control can be accessed and the values that were posted back are available. The UserControls in the sample contain a CheckBoxList and implement an interface that allows to retrieve the values that were selected by the user.
In most cases it is easier to find a different approach. Maybe you can use a MultiView control for your wizard that contains the UserControls for the wizard pages as static content. See this link for a description of how to use the MultiView control. If there are not too many (read unlimited) different UserControls to use, this approach is much more stable.
I was looking in the wrong place. Page.Form as opposed to Page.Request.Form. Due to the fact the checkboxlist is already defined in the user control, it's name is traceable in this variable. This way I can keep the current wizard structure.

How can I access this asp.net Panel control in a user control and make it visible?

I am a new ASP.NET Web Forms developer and I am struggling right now with hiding a part of the user control in some of the pages which have it based on certain factors.
ASP.NET code of the user control:
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlView" runat="server" CssClass="panel">
<span class="lead text-info">This is a simple test user control</span>
</asp:Panel>
<asp:Panel ID="pnlActions" runat="server" Visible="false">
<asp:Button ID="btnConfirm" runat="server" Text="Confirm" CssClass="btn btn-primary btn-lg"
OnClick="btnConfirm_Click" />
<asp:Button ID="btnReject" runat="server" Text="Reject" CssClass="btn btn-danger"
OnClick="btnReject_Click" />
<asp:Label ID="lblInfo" runat="server" Text="" CssClass="label label-info"></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Code-Behind of the user control:
protected void btnConfirm_Click(object sender, EventArgs e)
{
lblInfo.Text = "Confirmed";
}
protected void btnReject_Click(object sender, EventArgs e)
{
lblInfo.Text = "Rejected";
}
The asp.net panel with id "pnlActions" should be displayed based on the username of the user who is going to access the .aspx page that has this user control. So how can I do that?
Here's the ASP.NET code of the .aspx page:
<div class="row">
<div class="col-md-6">
<span class="lead">This is the user control</span>
<uc:TestUserControl ID="TestUserControl1" runat="server"></uc:TestUserControl>
</div>
<div class="col-md-6">
<p class="well">
The user control on the left side has an asp.net panel control which
has two buttons. These two buttons should be shown if the user
is an administrator, and they should be hidden for the rest of users.
This user control will be used on four pages across this test application.
</p>
</div>
</div>
Code-behind of the .aspx page:
string username = "JohnA";
protected void Page_Load(object sender, EventArgs e)
{
if (username == "JohnA")
{
//pnlActions control in the user control should be displayed
}
else
{
//pnlActions control should be hidden
}
}
These control specific actions should be placed in your user controls code behind, rather than in your pages layout, to provide more modularity.
Later the goal is to put all of these custom components in different variations on the page, thats the point of custom user controls.
You canĀ“t accomplish that by putting business logic of your individual components in the layout.
If you really want to do that you can do it by exposing your panels by public properties in your controls code behind or modifing the designer code(not always a good idea...).
You could read into this article:
http://www.codeproject.com/Articles/28783/Your-First-ASP-NET-Custom-Control
try to find control by id in user control code .
or there is a step to get the page control first who hosts the user control and then find the control by id from that page . once u have reference to your control you can definitely do all operations.
Please use the following line in the user control.
this.Master.FindControl("pnlView").Visible = true;

Fail to continously add new control into Panel/Placeholder during partial postback

I want to create a dynamic form where user has a button to click on it.
When the button clicked, it will trigger a partial postback and add a new control into a placeholder.
My problem is, when the button is clicked for the first time, it able to create a new control in the placeholder. But it will not create more than that even though i have clicked the button for few times.
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Add images" OnClick="Button1_Click" />
<asp:HiddenField ID="HiddenField1" runat="server" Value="1" />
<br />
<asp:Panel ID="PlaceHolder1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new FileUpload());
}
Unless a dynamically added control is added at the preinit or init stage, it does not persist beyond a post back. So when the button is clicked for the second time, the first added control is lost and then the button logic adds a control again, leaving you with one control every time. For a control added after the init stage, you would need to store its state and recreate it on each postback. This is described int this article:
http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i
You may also be able to achieve your goals without using dynamically added controls. One possible approach is to use a ListView control, add a FileUpload control to its ItemTemplate and add a new record to the list view data source every time the button is clicked.

Response.Redirect Same Page RadioButtonList SelectedItem

I'm trying to do a job filter for the list of jobs on our website. The filter for the job type is wrapped in an UpdatePanel and the button to apply the filters redirects back to the same page.
This is because I will be using the umbraco.library:RequestQueryString in the XSLT to populate the jobs list.
However, the querystring filter value doesn't seem to select the RadioButtonList. For example:
The page loads, but nothing happens because vt is null:
protected void Page_Load(object sender, EventArgs e)
{
string vt = Request.QueryString["vt"];
if (vt != null)
{
foreach (ListItem li in rblVacancyType.Items)
{
if (li.Value == vt)
{
li.Selected = true;
}
}
}
}
<asp:UpdatePanel ID="upSearchFilters" runat="server">
<ContentTemplate>
<p>
<asp:RadioButtonList ID="rblVacancyType" runat="server">
<asp:ListItem Text="All" Value="all"></asp:ListItem>
<asp:ListItem Text="Permanent" Value="permanent"></asp:ListItem>
<asp:ListItem Text="Temporary" Value="temporary"></asp:ListItem>
</asp:RadioButtonList>
</p>
</ContentTemplate>
</asp:UpdatePanel>
Here's the button:
<asp:ImageButton ID="ibFilters" ImageUrl="~/images/buttons/filter-button.png" OnClick="ibApplyFilters_Click" runat="server" />
Here's the procedure:
protected void ibApplyFilters_Click(object sender, EventArgs e)
{
Response.Redirect("/careers/join-us/?filters=true&vt=" + rblVacancyType.SelectedValue.ToString());
}
Yet when the page redirects the first time, nothing is selected, I click permanent, permanent gets selected. If I then select 'All' or 'Temporary' the selection doesn't change.
Any ideas?
Based on the behavior (it works the first time) I believe this describes what's happening:
MyPage.aspx (original load)
Page controls initialized to default
Page Load - No query string, no radio button selected
(user clicks button - causes postback)
MyPage.aspx (postback)
Page controls initialized to default
Radio Button Set from ViewState
Page Load - No query string, no radio button selected
ButtonClick - uses radio button setting, does response redirect
MyPage.aspx?VT=Permanent (load from redirect)
Page controls initialized to default
Page Load - Query string set, radio button selected
(user clicks button - causes postback)
MyPage.aspx?VT=Permanent (postback)
Page controls initialized to default
Radio Button Set from ViewState
Page Load - Query string set, radio button set to Permanent (Here is the problem)
ButtonClick - uses radio button setting, does response redirect
I believe a simple (if !IsPostback) will fix things
Sounds like postback values being re-applied. See this article on ASP.NET page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx.
Values for controls are re-applied via postback after page_load.
Due to the strange nature of code + postbacks the logic in Mark's answer seems to be quite accurate, but the suggested fix did not work as I had tried that as a possible solution. The below is a modification, but as far as I could see it works. Give it a try, it might work out for you.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="upSearchFilters" runat="server">
<ContentTemplate>
<p>
<asp:RadioButtonList ID="rblVacancyType" runat="server"
AutoPostBack="True">
<asp:ListItem Text="All" Value="all"></asp:ListItem>
<asp:ListItem Text="Permanent" Value="permanent"></asp:ListItem>
<asp:ListItem Text="Temporary" Value="temporary"></asp:ListItem>
</asp:RadioButtonList>
</p>
<p>
<asp:ImageButton ID="ibFilters" runat="server" CausesValidation="False"
Height="30px" OnClick="ibApplyFilters_Click" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
ibFilters.PostBackUrl = "~/WebForm1.aspx?filters=true&vt=" + rblVacancyType.Text;
string vt = Request.QueryString["vt"];
}
Important:
The way this is set up, it will maintain your selection, update the filter parameters in the url on button push, and then assign vt the correct value to be used on filtering anything else on your page.
You must change out my "~/WebForm1.aspx?filters=true&vt=" for your url as well.

Categories

Resources