Two updatePanels and popup extender which should not disappear after postback - c#

On my MasterPage I have 2 update panels which are surrounded with Panels. Two of them contain 'Details View' controls and some buttons.
On the other hand, I have one UpdatePanel which contains image buttons and link buttons.
The idea is that I'm fetching from the database the messages ( 2 kinds), showing them on the Page. When the user clicks on a button (LinkButton or ImageButton), he or she sees a 'Popup Control'. On the popup control, he or she can see the message details and if needed, cancel them or approve.
Here is where I am stuck. If I remove the ImageButtons from the UpdatePanels, I won't be able to refresh them without a full postback.
Should I have 'popup extensions' in the UpdatePanel with the ImageButtons, but then when I click on the button from 'popup panel' - it disappears ( there is no full postback, it just disappears) - it should just change the DetailsView page.
How do I make it work?
Thanks in advance !
(I need this solution because I want to use a timer to refresh LinkButtons )
here is my code behind :
protected void Page_Load(object sender, EventArgs e)
{
try
{
//here im pulling data from database and binding it with 'details view' controls, its not big deal so i think i don't have to show it?
wyswietl_powiadomienia_o_wydarzeniach();
wyswietl_ilosc_zaproszen_do_przyjaciol();
wyswietl_ilosc_nieodczytanych_wiadomosci();
}
catch (Exception)
{
}
}
protected void ButtonWczesniej_Click(object sender, EventArgs e)
{
DetailsViewEventsRequests.PageIndex = DetailsViewEventsRequests.PageIndex - 1;
ButtonDalej.Enabled = true;
wyswietl_powiadomienia_o_wydarzeniach();
}
protected void ButtonDalej_Click(object sender, EventArgs e)
{
//
DetailsViewEventsRequests.PageIndex = DetailsViewEventsRequests.PageIndex + 1;
ButtonWczesniej.Enabled = true;
wyswietl_powiadomienia_o_wydarzeniach();
}
protected void ButtonInvLeft_Click(object sender, EventArgs e)
{
DetailsViewIfFriends.PageIndex = DetailsViewIfFriends.PageIndex - 1;
}
protected void ButtonInvRight_Click(object sender, EventArgs e)
{
DetailsViewIfFriends.PageIndex = DetailsViewIfFriends.PageIndex + 1;
}
And my aspx: (only one updatepanel with detail's view because 2nd one is very simillar)
<div id="NotifyAreaWhite">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="NotifyAreaDiv">
<div id="NotifyDivMail">
<div id="NotifyLeftMSG"><asp:ImageButton ID="ImageButtonNotifyMsg" runat="server"
ImageUrl="~/images/msg.png" PostBackUrl="~/wiadomosci.aspx"
ToolTip="Wyslij wiadomosc" /></div>
<div class="NotifyRight"> <asp:LinkButton ID="LabelNotifyMsgNo" runat="server" Text="0" Font-Size="Large" PostBackUrl="~/wiadomosci.aspx"/></div>
</div>
<div class="NotifyDiv">
<div id="NotifyLeftFrend" class="NotifyLeft"> <asp:ImageButton ID="ImageButtonNotifyFrends" runat="server"
ImageUrl="~/images/friends.png"
ToolTip="Zaproszenia od znajomych." /></div>
<div id="NotifyRightFrend" class="NotifyRight"><asp:LinkButton ID="LabelNotifyFrendsNo" runat="server" Text="0" Font-Size="Large"/></div>
</div>
<div class="NotifyDiv">
<div id="NotifyLeftWyd" class="NotifyLeft"> <asp:ImageButton ID="ImageButtonWydarzenia" runat="server" ImageUrl="~/images/event.png" ToolTip="Zaproszenia do wydarzen." /></div>
<div id="NotifyRightWyd" class="NotifyRight"> <asp:LinkButton ID="LabelNotifyEventsNo" runat="server" Text="0" Font-Size="Large"/></div>
</div>
</div>
<asp:ModalPopupExtender ID="PanelZaproszeniaEventy_ModalPopupExtender"
runat="server" Enabled="true" OkControlID="ButtonZamknijOkno" CancelControlID="ButtonZamknijOkno"
TargetControlID="ImageButtonWydarzenia" PopupControlID="PanelZaproszeniaEventy"
BackgroundCssClass="NotifyPageTloClass"/> //extender showing Panel
<asp:ModalPopupExtender ID="PanelZaproszeniaEventy_ModalPopupExtenderCyfra"
runat="server" Enabled="true" OkControlID="ButtonZamknijOkno" CancelControlID="ButtonZamknijOkno"
TargetControlID="LabelNotifyEventsNo" PopupControlID="PanelZaproszeniaEventy"
BackgroundCssClass="NotifyPageTloClass"/>
<asp:ModalPopupExtender ID="PanelProsbyOznajomosc_ModalPopupExtender"
runat="server" Enabled="true" OkControlID="ButtonFrendCloseNotifier" CancelControlID="ButtonFrendCloseNotifier"
TargetControlID="ImageButtonNotifyFrends" PopupControlID="PanelProsbyOznajomosc"
BackgroundCssClass="NotifyPageTloClass"/>
<asp:ModalPopupExtender ID="PanelProsbyOznajomosc_ModalPopupExtenderCyfra"
runat="server" Enabled="true" OkControlID="ButtonFrendCloseNotifier" CancelControlID="ButtonFrendCloseNotifier"
TargetControlID="LabelNotifyFrendsNo" PopupControlID="PanelProsbyOznajomosc"
BackgroundCssClass="NotifyPageTloClass"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:Panel ID="PanelZaproszeniaEventy" runat="server" Width="318px" CssClass="NotifyWydTlo" >
<asp:UpdatePanel ID="UpdatePanelZaproszeniaEventy" runat="server" RenderMode="Block">
<ContentTemplate>
<asp:DetailsView ID="DetailsViewEventsRequests" runat="server" DataKeyNames="Charakterystyka" AutoGenerateRows="False" Height="17px" Width="313px" HorizontalAlign="Center" onitemcreated="DetailsViewEventsRequests_ItemCreated">
<Fields>
<asp:BoundField DataField="UserName" HeaderText="Zalozyciel" SortExpression="Nazwisko" />
<asp:BoundField DataField="Miasto" HeaderText="Gdzie?" SortExpression="Miasto" />
<asp:BoundField DataField="Data_ZalozeniaWydarzenia" HeaderText="Data wyslania" SortExpression="Miasto" />
</Fields>
<FooterTemplate>
</FooterTemplate>
<HeaderTemplate>
<div>
<div style="float:left;">
<asp:Label ID="LabelNazwaWydarzenia" runat="server"
Text='<%# Eval("Nazwa_Wydarzenia") %>'></asp:Label>
</div>
<div style="float:right; margin-left:5px;">
<asp:Button ID="ButtonZobacz" runat="server" CssClass="myButton" Text="Zobacz Wydarzenie" Font-Size="X-Small" Width="150px" ClientIDMode="AutoID" OnClick="ButtonZobacz_click" UseSubmitBehavior="True"/>
</div>
</div>
</HeaderTemplate>
<EmptyDataTemplate>
<table id="Table1" runat="server" style="border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px; color:#FF5041; margin-left:auto; margin-right:auto;">
<tr>
<td>Nie masz zadnych zaproszen.</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:DetailsView>
<table style="margin-left:auto; margin-right:auto;">
<tr>
<td>
<asp:Button ID="ButtonWczesniej" Width="69px" Height="41px" runat="server" Text="<<" OnClick="ButtonWczesniej_Click" CssClass="myButton" /></td> //button previous msg
<td>
<asp:Button ID="ButtonDalej" Width="69px" Height="41px" runat="server" Text=">>" ///button next msg
OnClick="ButtonDalej_Click" CssClass="myButton"/></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<div style="margin-left:auto; margin-right:auto; width: 112px;">
<asp:Button CssClass="myButton" ID="ButtonZamknijOkno" Width="100%" //button closing popup
Height="41px" runat="server" Text="ZAMKNIJ"/>
</div>
</asp:Panel>
I hope i described it well. Sorry For my weak english and some Polish words in code :)

As i should do at the begining i made this example on empty page and try something else.. mode="Conditional" did the trick.
I should give that code before, not that long one :)
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:HyperLink ID="HyperLinkPanelOn" runat="server">click here to show popup</asp:HyperLink>
<asp:ModalPopupExtender ID="PanelZaproszeniaEventy_ModalPopupExtenderCyfra"
runat="server" Enabled="true" OkControlID="ButtonClose" CancelControlID="ButtonClose"
TargetControlID="HyperLinkPanelOn" PopupControlID="Panel1" BackgroundCssClass="NotifyPageTloClass" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanelPopUp" runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="postback" />
<asp:Button runat="server" Text="postback" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="ButtonClose" runat="server" Text="Zamknij" />
</asp:Panel>
So simple.. I thought it's something bigger :/

Related

Asp.NET: How to keep focus on textbox in a nested Update Panel

I am working on making a semi simple post and reply/forum pages in asp.net(with C#). Everything works however when I went to add update panels it makes me want to throw my head into a wall.
I use a DataList to display the posts. I use a form consisting of two textboxes and a button to insert a new post. One textbox if for the name, and the other for the message.
First update panel I added (nested) is to provide a character count for the post. I have a label in the Content and it is triggered by the textboxes textchanged event. The textbox 'txtMessage' also has a java-script function run 'onkeyup' to keep the focus on the textbox when typing. I limit the characters at 1000.
The next update is to surround the DataList so that it does not post back everytime (if not used and the back button is hit it will go back and visually remove each post which is not a good design practice). However when I just put the panel around the DataList it did not postback the insert form so the boxes were not cleared. Which I would like to be done, so I wrapped everything then by this updatepanel, which then made the character count update panel nested by this one. This now works, but the focus is taken off of the txtMessage box each time the textchanged event fires. So the JavaScript is not firing now?
I have moved the opening and closing of the update panel countless times and have tried different fixes, so any further suggestions would help. The code is below.
ForumT.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ForumT.aspx.cs" Inherits="UPE_Site_v1.ForumT" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="headPlaceHolder" runat="server">
<script type="text/javascript">
function reFocus(id) {
__doPostBack(id, '');
document.getElementById(id).blur();
document.getElementById(id).focus();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetPosts" TypeName="TimeTrackerRepository" DataObjectTypeName="System.Guid" DeleteMethod="DeletePost"> </asp:ObjectDataSource>
<asp:UpdatePanel ID="upDataList" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:DataList ID="DataList2" runat="server" CellPadding="4" DataSourceID="ObjectDataSource1"
ForeColor="#333333" OnItemCommand="DataList2_ItemCommand" OnItemDataBound="DataList2_ItemDataBound"
DataKeyField="PostID" OnItemCreated="DataList2_ItemCreated">
<AlternatingItemStyle BackColor="White" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#D4EBD4" />
<ItemTemplate>
<div class="row">
<div class="col-xs-12 col-sm-6">
Name: <strong><%# Eval("Name") %></strong>
</div>
<div class="col-xs-12 col-sm-6">
<%# Eval("TimePosted") %>
</div>
<div class="col-xs-12" style="word-break: break-all">
<%# Eval("Message") %>
</div>
</div>
<br />
<asp:Button ID="btnDelete" CssClass="btn btn-warning" runat="server" Text="Delete" CommandArgument='<%# Eval("PostID") %>' CommandName="DeleteItem" />
<asp:LinkButton CssClass="btn btn-primary" ID="lkbtnFullPost" runat="server" Text="See Full Post" CommandArgument='<%# Eval("PostID") %>' CommandName="FullPost"></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
</asp:DataList>
</div>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<br />
<br />
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">
<p>Add a post to this forum:</p>
<div class="form-group">
<asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label>
<asp:TextBox CssClass="form-control" ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
</div>
<%--<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>--%>
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Message: "> </asp:Label>
<asp:TextBox onkeyup="reFocus(this.id);" CssClass="form-control" ID="txtMessage" runat="server" TextMode="MultiLine" Rows="4" OnTextChanged="txtMessage_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="Character limit is 1000 characters."
ValidationGroup="Application" Display="Dynamic" ForeColor="Red"
ValidationExpression=".{0,1000}">
</asp:RegularExpressionValidator>
</div>
<br />
<%--</div>
</div>--%>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<%--<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">--%>
<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCharacterCount" runat="server">0/1000</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtMessage" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ValidationGroup="Application" CssClass="btn btn-default" ID="btnPost" runat="server" Text="POST IT" OnClick="btnPost_Click" />
<asp:Label ID="lblError" runat="server" Text="" CssClas="Error" ForeColor="Red"></asp:Label>
</div>
</div>
<br />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
ForumT.aspx.cs
only including the textchanged event
protected void txtMessage_TextChanged(object sender, EventArgs e)
{
lblCharacterCount.Text = txtMessage.Text.Count().ToString() + "/1000";
if (txtMessage.Text.Count() >= 1000)
{
lblCharacterCount.ForeColor = System.Drawing.Color.Red;
}
else
{
lblCharacterCount.ForeColor = System.Drawing.Color.Black;
}
}
Sorry for the code being a little sloppy. Also side not, I am using bootstrap so that is what all of the div's are for
I was facing the same issue as I needed to set focus on the textbox after postbacks in update panel. So I researched over internet & found this Javascript code. I tried it & it is working perfectly. It adds event listener for update panel for before & after postback. Gets textbox id before postback & set it after completion of postback.
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof (window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof (document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof (focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof (lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
Just use this code in your script on aspx page.
You say your javascript is not working. When using update panels and js you will need to rebind your js subscribed events.
Reference: jQuery $(document).ready and UpdatePanels?

Asp .Net UpdatePanel not working

I am using an UpdatePanel to show some controls that are normally hidden.
This is the code that I am using:
<asp:LinkButton runat="server" class="btn blue h27" CausesValidation="false" ID="lnkSuggestArticle"
OnClick="lnkSuggestArticle_Click"><%=Supplier.GetResource("Answers_lnkSuggestArticle")%> <i class="icon icon_next_02 fr"></i></asp:LinkButton>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div class="infoRequest" id="divSuggestion" runat="server" visible="false">
<br class="clearfix" />
<h3>
Please provide the information you want to see on our support site:</h3>
<br class="clearfix" />
<asp:TextBox runat="server" ID="txtSuggestArticle" Rows="10" ValidationGroup="s" Width="100%"
TextMode="MultiLine"></asp:TextBox>
<div id="divEmailAddress" runat="server" visible="false">
<br />
<h3>
Please enter your email address</h3>
<asp:TextBox runat="server" ID="txtEmailAddress" Rows="1" ValidationGroup="s" CssClass="suggestionEmail"
TextMode="SingleLine"></asp:TextBox>
<br />
</div>
<br />
<asp:Label runat="server" ID="lblSugestedArticleError" ForeColor="Red" Visible="false"></asp:Label>
<asp:Label runat="server" ID="lblMessage" ForeColor="Red"></asp:Label>
<br />
<asp:LinkButton ID="btnSaveSuggestion" ValidationGroup="s" runat="server" OnClick="btnSaveSuggestion_Click"
CssClass="btn blue fr"><%=Supplier.GetResource("createticket_btnSuggest")%> <i class="icon icon_next_02 fr"></i></asp:LinkButton>
<%--<input type="submit" value="Suggest" class="btnSuggest" />--%>
<br />
<br />
<p id="notice" runat="server">
<asp:Label runat="server" ID="lblSuggestionNote" /></p>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lnkSuggestArticle" />
</Triggers>
</asp:UpdatePanel>
When the user clicks the lnkSuggestArticle button I execute the following code:
protected void lnkSuggestArticle_Click(object sender, EventArgs e)
{
divSuggestion.Visible = true;
if ((WFSS.DataAccess.Entities.Customer)Session["__currentCustomer"] == null)
{
divEmailAddress.Visible = true;
}
}
But it doesn't update the page. The div still stays hidden when the user clicks the suggest button.
protected void lnkSuggestArticle_Click(object sender, EventArgs e)
{
divSuggestion.Visible = true;
if (Session["__currentCustomer"] == null)
{
divEmailAddress.Visible = true;
}
}
It turns out that there was a bug in Visual Studio. I had commented a piece of code in the aspx file. Turns out even though it appeared to be commented the code still executed which caused another update panel to be added which gave me an error in javascript.

How to show a ModalPopup when clicked on button?

When i click on a Button i must show a modal popup
ASPX code:
<section>
<asp:Button ID="btnShowPopup" runat="server" Text="EditContextMenu" Visible="true" OnClick="btnShowPopup_Click" />
<ajax:ModalPopupExtender ID="ModalPopupContextInfo" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlpopupContextInfo"
CancelControlID="imgClose" BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlpopupContextInfo" runat="server" BackColor="White" Height="560px" Width="400px" Style="display: none" >
<div class="contextMenu_edit" >
<div class="context_menu">
<p>Port</p>
<asp:TextBox ID="txtCMEditPort" runat="server" MaxLength="10" Width="131px" TabIndex="1"></asp:TextBox>
<div class="clear"></div>
<p>ProformaETA</p>
<asp:TextBox ID="txtCMEditProformaETA" runat="server" MaxLength="10" Width="131px" TabIndex="1"></asp:TextBox>
<asp:ImageButton ID="imgbtnCMEditProformaETA" runat="server" ImageUrl="~/image_repository/calendarIcon.jpg" />
<ajax:CalendarExtender ID="ajaxcalProfrmaETA" runat="server" TargetControlID="txtCMEditProformaETA" PopupButtonID="imgbtnCMEditProformaETA" Format="dd-MMM-yyyy"></ajax:CalendarExtender>
<div class="clear"></div>
<p>ProformaETD</p>
<asp:TextBox ID="txtCMEditProformaETD" runat="server" MaxLength="10" Width="131px" TabIndex="1"></asp:TextBox>
<asp:ImageButton ID="imgbtnCMEditProformaETD" runat="server" ImageUrl="~/image_repository/calendarIcon.jpg" />
<ajax:CalendarExtender ID="ajaxcalProfrmaETD" runat="server" TargetControlID="txtCMEditProformaETD" PopupButtonID="imgbtnCMEditProformaETD" Format="dd-MMM-yyyy"></ajax:CalendarExtender>
</div>
</div>
</asp:Panel>
</section>
Code Behind :
protected void btnShowPopup_Click(object sender, EventArgs e)
{
ModalPopupContextInfo.Show();
}
This is Not working.
You've forgotten to define imgClose control, which you use as CancelControlID in ModalPopupExtender.
<ajax:ModalPopupExtender ID="ModalPopupContextInfo" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlpopupContextInfo"
CancelControlID="imgClose" BackgroundCssClass="modalBackground">
That's why your extender does not work.
Also you need to set active index for Model Popup Extender. Mostly it
ASPX Page :
"asp:button id="Button1" runat="server" text="DOWNTIME" cssclass="FormButton" width="20%"
"ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" BackgroundCssClass="ModalPopupBG"
runat="server" TargetControlID="Button1" CancelControlID="btnCancel1" PopupControlID="Panel1" Drag="true" PopupDragHandleControlID="PopupHeader"
Then
"asp:multiview id="MultiViewExpanse" runat="server""
asp:View ID="ViewInput" runat="server"
/asp:View
/asp:multiview
C#
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
ModalPopupContextInfo.ActiveViewIndex = 0;
}
}
}
It works...fine...If still want some..help.... Ping me...

Form submits on browser refresh

I am having trouble to find a solution to stop form submission on click of the browser's refresh button.
This is the Login form I have:
<asp:Login ID="EMSLogin" runat="server" OnAuthenticate="EMSLogin_Authenticate">
<LayoutTemplate>
<asp:Panel ID="Panel1" runat="server" CssClass="wrapper">
<asp:Panel ID="Panel2" runat="server" CssClass="holder">
<asp:Panel ID="Panel3" runat="server" CssClass="loginBox one_edge_shadow">
<h1>
Login Credentials</h1>
<asp:Panel ID="Panel4" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel5" runat="server" CssClass="label">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel6" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="UserName" runat="server" Height="16px" Width="165px" Font-Size="14px"
Font-Names="Arial Sans-Serif" ToolTip="Enter your valid login name" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
</asp:Panel>
<asp:Panel ID="Panel7" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel8" runat="server" CssClass="label">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel9" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="Password" runat="server" TextMode="Password" Height="16px"
Width="165px" Font-Size="14px" Font-Names="Arial Sans-Serif" ToolTip="Enter your valid password" />
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
<telerik:RadButton ID="LoginButton" runat="server" CommandName="Login" Text="Log In"
CssClass="loginButton" Font-Size="14px" Width="100px" ValidationGroup="EMSLogin"
ToolTip="Click to log in" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</LayoutTemplate>
</asp:Login>
And in the backend:
protected void Page_Load(object sender, EventArgs eventArgs) {
log.Info("=============INSIDE Page_Load======");
DataBind();
LoginErrorWindow.VisibleOnPageLoad = false;
}
protected void EMSLogin_Authenticate(object sender, AuthenticateEventArgs e) {
log.Info("=============INSIDE EMSLogin_Authenticate======");
RadTextBox UserName = EMSLogin.FindControl("UserName") as RadTextBox;
RadTextBox Password = EMSLogin.FindControl("Password") as RadTextBox;
if (Membership.ValidateUser(UserName.Text, Password.Text)) {
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
} else {
LoginErrorWindow.NavigateUrl = EMSApplication.Web.Utils.NavigationUtils.GetLoginErrorDialogURL();
LoginErrorWindow.VisibleOnPageLoad = true;
}
}
Now after one login failed if I press the refresh button the method EMSLogin_Authenticate is executing again. And before reload it is showing:
How can I solve this?
Do a Response.Redirect to an error page after the login has failed.
See the PRG pattern on Wikipedia.
Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more intuitive interface for user agents (users). PRG implements bookmarks and the refresh button in a predictable way that does not create duplicate form submissions.

Update Panel and Dropdown Selected Index change Issue

I have two dropdowns categories and subcategories on my page. Also I have an htmleditor on the same page. Below is my aspx
<div class="clearfx">
</div>
<div>
<label>
Description :
</label>
<div style="padding-left: 10px; margin-left: 146px;">
<cc:HtmlEditor ID="Editor" runat="server" Height="600px" Width="850px" EnableViewState="true" />
</div>
</div>
<div class="clearfx">
</div>
<div>
<asp:UpdatePanel runat="server" ID="up" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<label>Category : </label>
<asp:DropDownList runat="server" ID="Categories" Width="200px" AutoPostBack="True"
OnSelectedIndexChanged="CategoriesSelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvCountry" runat="server" ErrorMessage="Choose a category."
ControlToValidate="Categories" Display="None" EnableTheming="False" EnableViewState="False"
InitialValue="-1" SetFocusOnError="True" ValidationGroup="grpReg"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="rfvCountry_ValidatorCalloutExtender" runat="server"
Enabled="True" TargetControlID="rfvCountry">
</asp:ValidatorCalloutExtender>
<asp:ImageButton runat="server" ID="Refresh" ImageAlign="AbsMiddle"
ImageUrl="~/cdn/images/refresh.png" onclick="RefreshClick"/>
<span class="helptext">(click on refresh image, incase subcategories do not load.)</span>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="clearfx">
</div>
<div>
<label>
Sub Category :
</label>
<asp:DropDownList runat="server" ID="SubCategories" Width="200px">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Choose a sub category."
ControlToValidate="SubCategories" Display="None" EnableTheming="False" EnableViewState="False"
InitialValue="-1" SetFocusOnError="True" ValidationGroup="grpReg"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server" Enabled="True"
TargetControlID="RequiredFieldValidator2">
</asp:ValidatorCalloutExtender>
</div>
What I am doing is that, On the selected index change of the categories dropdown i am populating subcategories. to suppress post back i am using an Update Panel, But my problem is that,the selected index change is fired but the dropdown subcategories does not gets binded. When I remove the update panel, then its works fine, but my html editor looses its value, even having its own and Page enableviewstate = true. Please help me.
My Codebehind methods are:
Dropdown Selected Index Change Event:
protected void CategoriesSelectedIndexChanged(object sender, EventArgs e)
{
if (Categories.SelectedIndex > 0)
{
BindSubCategory(Common.ParseInt(Categories.SelectedItem.Value));
}
else
{
SubCategories.SelectedIndex = 0;
SubCategories.Items.Clear();
}
}
Page Load Event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
BindCategories();
}
}
private void BindCategories()
{
List<Category> cat = _categoryRepository.GetAll().ToList();
Common.BindDropdown(cat, Categories); // static method
}
public static class Common
{
/// <summary>
///
/// </summary>
/// <param name="list"></param>
/// <param name="ddl"></param>
public static void BindDropdown(IList list, DropDownList ddl)
{
if (list.Count>0)
{
ddl.DataSource = list;
ddl.DataTextField = "Name";
ddl.DataValueField = "Id";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("---Select---", "-1"));
}
}
}
You need to put the Subcategories in another UpdatePanel and add the proper triggers (set the second panel to trigger on the Categories dropdowns selectedindexchanged event).
<Triggers>
<asp:AsyncPostBackTrigger ControlId="Categories"
EventName="SelectedIndexChanged" />
</Triggers>
sample here
Try this:
<div class="clearfx">
</div>
<div>
<label> Description : </label>
<div style="padding-left: 10px; margin-left: 146px;">
<cc:HtmlEditor ID="Editor" runat="server" Height="600px" Width="850px" EnableViewState="true" />
</div>
</div>
<div class="clearfx">
</div>
<asp:UpdatePanel runat="server" ID="up" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<div>
<label>Category : </label>
<asp:DropDownList runat="server" ID="Categories" Width="200px" AutoPostBack="True"
OnSelectedIndexChanged="CategoriesSelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvCountry" runat="server" ErrorMessage="Choose a category."
ControlToValidate="Categories" Display="None" EnableTheming="False" EnableViewState="False"
InitialValue="-1" SetFocusOnError="True" ValidationGroup="grpReg"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="rfvCountry_ValidatorCalloutExtender" runat="server"
Enabled="True" TargetControlID="rfvCountry">
</asp:ValidatorCalloutExtender>
<asp:ImageButton runat="server" ID="Refresh" ImageAlign="AbsMiddle"
ImageUrl="~/cdn/images/refresh.png" onclick="RefreshClick"/>
<span class="helptext">(click on refresh image, incase subcategories do not load.)</span>
<div class="clearfx">
</div>
<div>
<label> Sub Category : </label>
<asp:DropDownList runat="server" ID="SubCategories" Width="200px">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Choose a sub category."
ControlToValidate="SubCategories" Display="None" EnableTheming="False" EnableViewState="False"
InitialValue="-1" SetFocusOnError="True" ValidationGroup="grpReg"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server" Enabled="True"
TargetControlID="RequiredFieldValidator2">
</asp:ValidatorCalloutExtender>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>

Categories