I created a page, which allows users the option to show or hide it's content sections via a show/hide button. After clicking the show/hide button, the nested panels/content becomes visible or invisible based on the button selected, then the user may save the page by clicking a save button. Problem - (no errors) but, the page is not saving the users changes into the cookie. The page contains 2 panel controls that are nested in one main Panel control.
//Front End code - The save button
<asp:Button ID="savButton" runat="server" Text="Save" onclick="savButton_Click" />
//psuedo code - The Panels
<asp:Panel ID="pnlSaveContent" runat="server"> //main Panel control
<asp:Panel ID="pnlWeatherAppCtrl" runat="server"> // panel content 1
<div>Weather App Content</div>
</Panel>
<asp:Panel ID="StockAppCtrl" runat="server"> // panel content 2
<div>Stock App Content</div>
</Panel>
</Panel>
//Back-end code:
protected void Page_Load(object sender, EventArgs e)
{
//get the cookie
if ((Request.Cookies["preferences"] != null))
{
pnlSaveContent.ID = Request.Cookies["preferences"]["savePg"];
}
}
//set cookie
protected void savButton_Click(object sender, EventArgs e)
{
Response.Cookies["preferences"]["savePg"] = pnlSaveContent.ID;
Response.Cookies["preferences"].Expires = DateTime.MaxValue;
}
//end code
...the issue: The page is not saving the changes of the main panel control. Could someone please provide some guidance as to what I’m doing wrong?
Don't forget to save the cookie with Response.Cookies.Add:
protected void savButton_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["preferences"] != null ?
Request.Cookies["preferences"] :
new HttpCookie("preferences");
c.Values["savePg"] = pnlSaveContent.ID;
c.Expires = DateTime.MaxValue;
Response.Cookies.Add(c);
}
As for your comment... I'm not quite sure what you are trying to do, but maybe it is this. This will set the visibility of the panel depending on the value of the cookie (visibility is false if the ID matches the value of cookie).
protected void Page_Load(object sender, EventArgs e)
{
//get the cookie
if ((Request.Cookies["preferences"] != null))
{
pnlSaveContent.Visible = !(pnlSaveContent.ID == Request.Cookies["preferences"]["savePg"]);
}
}
Related
I have an ajax tab container with 3 tabs.the problem is that when I make the first tab invisible,it makes the entire tab container invisible.
i have something like
<tk:TabContainer ID="TabContainer1" runat="server" >
<tk:TabPanel ID="Tabpanell" runat="server" >
</tk:TabPanel>
<tk:TabPanel ID="Tabpanel2" runat="server" >
</tk:TabPanel>
<tk:TabPanel ID="Tabpanel3" runat="server" >
</tk:TabPanel>
</tk:TabContainer>
and in code behind,on page load i need to show only some tabpanels based on condition that is..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!CheckViewPermissionTab1())
{
Tabpanel1.visible=false;
}
}
}
but when i try to set the first tabpanel's visibilit to false ,the entire tab container gets hidden.There is no problem whwn the second or third panel's visibility is set to false.
The problem is tabcontainer need atleast a tab should be active otherwise it will go invisible so if you set a tab to visible=false, then you have to set any other tab to be active.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!CheckViewPermissionTab1())
{
Tabpanel1.visible=false;
TabContainer1.ActiveTab = Tabpanel2;
}
}
}
Try the above code.
We have a user control that has a button. We use this user control on different aspx pages. We want the button to behave differently on different pages (dynamically). How might I achieve this goal?
It can be done using event in aspx.cs.
Suppose I have a button on user control
<asp:Button ID="btnClick" runat="server" Text="Click Me" onclick="btnClick_Click" />
on the user control code behind you can write as follows
public event EventHandler ButtonClickDemo;
protected void btnClick_Click(object sender, EventArgs e)
{
ButtonClickDemo(sender, e);
}
No on your aspx.cs content page you can use it as follows
protected void Page_Load(object sender, EventArgs e)
{
Demo1.ButtonClickDemo += new EventHandler(Demo1_ButtonClickDemo);
}
protected void Demo1_ButtonClickDemo(object sender, EventArgs e)
{
Response.Write("It's working");
}
Where Demo.ascx is the user control, so you can write Demo1.ButtonClickDemo
Depending upon how dynamic you want this functionality to be, it may be easier to simply create a property on your user control that would be set by your ASPx (if you can pass the information declaratively) or your codebehind (if you need to pass it programmatically). c.f. http://msdn.microsoft.com/en-us/library/26db8ysc.aspx for more information on creating user control properties.
I want to keep selected item after page reload:
Excerpt from .aspx:
<asp:DropDownList ID="MyDropDown" runat="server" AutoPostBack="true"
onselectedindexchanged="MyDropDown_SelectedIndexChanged">
</asp:DropDownList>
Exerpt from .cs in page_load
if (!IsPostBack)
{
PopulateDropDownList();
}
with
private void PopulateDropDownList()
{
MyDropDown.Items.Add("1");
MyDropDown.Items.Add("2");
}
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
Response.Redirect refresh the page and you will loose view state that will have selected index. You can put the selected index in session before redirecting.
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Session["MyDropDownSelectedIndex"] = MyDropDown.SelectedIndex.ToString();
Response.Redirect(Request.RawUrl);
}
You need to populate the drop down list in the Page init event. If you do that during Page load event the view state cannot be restored correctly (because the drop down list is not populated before Page load event) so the on selected index changed event cannot be fired.
EDIT: you may want to cache the data which populate the drop down list to save some around trip to the database. I think you do not need to redirect in the on selected index changed event too.
I have an asp.net application, where the user would click a button and launch another page (within the same application). The issue I am facing is that the original page and the newly launched page should both be launched.
I tried response.redirect, but that tends to unload the original page.
Any suggestions?
This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />
Edited and fixed (thanks to Shredder)
If you mean you want to open a new tab, try the below:
protected void Page_Load(object sender, EventArgs e)
{
this.Form.Target = "_blank";
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Otherpage.aspx");
}
This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.
-J
If you'd like to use Code Behind, may I suggest the following solution for an asp:button -
ASPX Page
<asp:Button ID="btnRecover" runat="server" Text="Recover" OnClick="btnRecover_Click" />
Code Behind
protected void btnRecover_Click(object sender, EventArgs e)
{
var recoveryId = Guid.Parse(lbRecovery.SelectedValue);
var url = string.Format("{0}?RecoveryId={1}", #"../Recovery.aspx", vehicleId);
// Response.Redirect(url); // Old way
Response.Write("<script> window.open( '" + url + "','_blank' ); </script>");
Response.End();
}
Use an html button and javascript? in javascript, window.location is used to change the url location of the current window, while window.open will open a new one
<input type="button" onclick="window.open('newPage.aspx', 'newPage');" />
Edit: Ah, just found this: If the ID of your form tag is form1, set this attribute in your asp button
OnClientClick="form1.target ='_blank';"
You should use:
protected void btn1_Click(object sender, EventArgs e)
{
Response.Redirect("otherpage.aspx");
}
For a "dashboard" module I need to dynamically load user controls based on criteria as the user enters the page (role, etc). The problem is that the events are not being fired at all from the controls
As I understand it I need to load the controls in the OnPreInit method of the dashboard page, however I cannot get a reference to the Placeholder control at this point of initialization (i.e. I get a NullReferenceException); trying to load the Placeholder dynamically via Page.FindControl gives me, ironically, a StackOverflowException.
I've tried loading the controls in PreRender and OnInit as well but the events in the controls are not wired up properly and will not fire.
The code is basically this:
// this does not work; if I try to access the placeholder control itself
// ("phDashboardControls") I get a NullReferenceException, if I try
// Page.FindControl("phDashboardControls") I get a StackOverflowException
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Control ph = Page.FindControl("phDashBoardControls"); // Placeholder
if (ph != null)
{
// GetControlsToLoad just instantiates the controls and returns
// an IList<Control>. Eventually it will have logic to
// determine which control needs to be loaded based on user role etc.
foreach (Control control in GetControlsToLoad())
{
ph.Controls.Add(control);
}
}
}
// IModularControl is a custom interface defining a single
// Initialize method to set up a control...
private void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.phDashboardControls.Controls)
{
if (control is IModularControl)
((IModularControl)control).Initialize(this.CompanyID);
}
}
I've successfully loaded controls dynamically in Page_Load before. The only thing I found I had to be careful of was to ensure that if I did a postback, the same controls were loaded in subsequent page_load to ensure that the view state didn't get corrupted... all events etc worked as expected. In my case the controls flow ended up something like this:
page_load - load control a
(do something which causes postback and event x to fire)
page_load - make sure you load control a
event_x - clear control a, load control b
(do something which causes postback)
page_load - make sure you load control b
...
it meant loading controls you fully intented discarding, but was the only way I could find to not corrupt the viewstate...
If you have a page with PlaceHolder1 and Label1 in it, then the following code causes the button click event to fire just fine:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicButton = new Button() { Text = "Click me" };
dynamicButton.Click +=new EventHandler(dynamicButton_Click);
PlaceHolder1.Controls.Add(dynamicButton);
}
void dynamicButton_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked button";
}
Behaves the same with a user control:
WebUserControl ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Click Me" onclick="Button1_Click" />
WebUserControl code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked Button";
}
parent control that loads the child control:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicControl = Page.LoadControl("~/WebUserControl.ascx");
PlaceHolder1.Controls.Add(dynamicControl);
}
Just FYI the issue had to do with validation; the events weren't firing properly because some of the validation controls (there were a ton) weren't configured to only apply to that control.