ASP.Net: Ajax registration question - asp.net

I worked with: ASP.Net: Ajax check for registration as a user?
It has a few errors, I don't understand:
1) It worked only one time for one textbox. If the textbox is edited a second time, the breakpoint will not be hited. Why?
2) For my Email, I have a check, that there is no duplicate, when there is one, there should the set an error panel visible, but it don't show.
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
}

When the update mode is conditional
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional"> // here the updatemode is conditional ...
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
You need to call
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
up1.Update(); // call to update the update panel "up1"
}
Sorry I'm a bit rusty, it's a while since I've used update panels.

After an update panel updates you must reinitialise the javascript on the html elements inside it.
So, to the end of your method you could add:
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
// Re-init javascript
ScriptManager.RegisterStartupScript(Type, String, "add onchange js here", Boolean);
}
see http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

Related

Why isn't my code-behind working properly?

Here's my code-behind file for a web form. I can't get certain arguments to work properly with my form.
protected void btn_Submit_Click(object sender, EventArgs e)
{//Enter arguments here...
}
protected void btn_Clear_Click(object sender, EventArgs e)
{
Response.Redirect("~/ContentRequest/BMC_PR_Event.aspx", true);
}
protected void ShowForm()
{
Open.Visible = true;
Success.Visible = false;
Failure.Visible = false;
}
protected void ShowSuccess()
{
Open.Visible = false;
Success.Visible = true;
Failure.Visible = false;
}
protected void ShowFailure()
{
Open.Visible = false;
Success.Visible = false;
Failure.Visible = true;
}
}
Here's the code I'm trying to get it to work with...
<asp:Button TabIndex="12" Text="Submit Request" ID="Button1" CssClass="submit" OnClientClick="return validateForm();" runat="server" onclick="btn_Submit_Click"></asp:Button>
<asp:Button TabIndex="13" Text="Clear Fields" ID="Button2" CssClass="clear" UseSubmitBehavior="false" runat="server" onclick="btn_Clear_Click"></asp:Button>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</asp:Panel>
<asp:Panel ID="Success" Visible="false" runat="server">
<div class="message"><p>Your submission was sucessful.</p><p>An email receipt has been sent to the address provided with the details of this request.</p><p>Thank you.</p></div>
</asp:Panel>
<asp:Panel ID="Failure" Visible="false" runat="server">
<div class="message">
<p>There was an error with your request. If this persists, please report your trouble to _OHE Web Strategies.</p>
Not sure what else I can do here...
--Edit--
This is the error I get...
From the code you have pasted, i cannot see a Panel control with the ID 'Open'. Please do one of the following.
If you need another Panel for the 'open' functionality, add another asp:Panel with the is 'Open'
If you have removed the Open panel once you had, remove the code (from code behind in your case) related to that.
Best of luck
James

ASP.Net AJAX UpdatePanel not working with Repeater and RadioButtons

I have a repeater which includes a radio button in each item, and the whole thing sites inside an update panel. When I select a radio button the whole page reloads. Why is it not just updating the update panel. I've reduced this to a pretty simple example to avoid clutter. Code here...
ASPX...
<asp:ScriptManager ID="SM1" runat="server" />
<asp:UpdatePanel ID="up1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater runat="server" ID="history">
<ItemTemplate>
<asp:RadioButton runat="server" ID="radioButton" AutoPostBack="true" GroupName="HistoryGroup" OnCheckedChanged="RadioButton_CheckChanged" /><br />
</ItemTemplate>
</asp:Repeater>
<p><asp:Literal runat="server" ID="output" /></p>
</ContentTemplate>
</asp:UpdatePanel>
Code...
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> list = new List<int>();
for (int i = 0; i < 20; i++)
list.Add(i);
history.DataSource = list.ToArray();
history.DataBind();
}
}
protected void RadioButton_CheckChanged(Object sender, EventArgs e)
{
output.Text = DateTime.Now.ToString();
}
}
Setting ClientIDMode=Auto on the RadioButton should fix it (it's an infamous .NET bug, http://connect.microsoft.com/VisualStudio/feedback/details/584991/clientidmode-static-in-updatepanel-fails-to-do-async-postback)
please add up1.Update() after output.Text = DateTime.Now.ToString(). Your RadioButton is not the trigger for updatepanel
Turns out the solution was to remove the GroupName from the RadioButton. When I remove this tag it fires asynchronously and just updates the panel. I don't actually need this tag anyway (due to the known bug where GroupName doesn't work on RadioButtons in Repeaters) as I handle the grouping within my click event (i.e. uncheck any other RadioButtons of the same name in other repeater items).

A variable declared at class level but initialized in page_load loses its scope in a button_click eventhandler?

im new to asp.net.. please bear with me if ma question is way too trivial!!! :)
im using an accordian control within an update panel. and i also have a button to save some data frm the accordian control! - This complete is a user control which is used in another .aspx page.
now in the page_load event of the user control i initialize my database connection which works absolutely fine while loading data to the accordian.. but when i click on save, in the save button click even handler the database connection object is always null..!! (even though it is initialized in the page_load) please help..
.ascx is as here:
<asp:UpdatePanel ID="PrefPanel" runat="server" >
<ContentTemplate>
<ajaxToolkit:Accordion ID="PrefAccordion" runat="server" HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent"
BackColor="#E8EAF7" Height="530px" Width="500px" AutoSize="None" RequireOpenedPane="false"
BorderStyle="Solid" BorderWidth="1" BorderColor="Black">
<Panes>
<ajaxToolkit:AccordionPane ID="ProjCategoryPaneID" runat="server">
<Header > Project Category</Header>
<Content>
<asp:Panel ID="ProjCategoryPanel" runat="server" Width="100%">
<table align="center" width="100%">
<tr></tr>
<tr>
<td align="left">
<asp:CheckBoxList RepeatDirection="Vertical" TextAlign="Left" ID="ProjCategoryItem1" runat="server" AutoPostBack="false" CausesValidation="false" />
</td>
</tr>
</table>
</asp:Panel>
</Content>
</ajaxToolkit:AccordionPane>
<asp:Button ID="btnSavePref" CssClass="buttonsmall" runat="server" Text="Save" Width="60px" OnClick="btnSavePref_Click"/>
<asp:Button ID="btnCancelPref" CssClass="buttonsmall" runat="server" Text="Cancel" Width="60px" />
</ContentTemplate>
</asp:UpdatePanel>
the code behind is as here:
public partial class UserPreferences : System.Web.UI.UserControl
{
private EAReportingDAL m_DataAccessLayer = null;
// Projects Category
Panel projectCategoryPanel;
CheckBoxList projectCategoryList;
protected void Page_Load(object sender, EventArgs e)
{
String connectionString = WebConfigurationManager.ConnectionStrings ["BSCDB"].ConnectionString;
m_DataAccessLayer = new EAReportingDAL(connectionString);
LoadUserPreferences();
}
protected void btnSavePref_Click(object sender, EventArgs e)
{
string userName = this.Page.User.Identity.Name;
DataSet availabeData = m_DataAccessLayer.GetUserPreferences(this.Page.User.Identity.Name, Constants.ProjectsUIView);
}
}
in the button click event handler btnSavePref_Click() the the db connection object m_DataAccessLayer is always null, but whereas the same object in LoadUserPreferences() [which i haven't pasted here though] works fine! plz guide me where im wrong or if someone needs more details!!
I'm not very familiar with UpdatePanel mechanics but maybe you defined it in such a way that it bypass the Page_Load method.
What I suggest is moving the code create the data access layer to separate method then calling this method from both the page load and button click handler:
private void InitDataAccess()
{
//ignore if already created
if (m_DataAccessLayer != null)
return;
String connectionString = WebConfigurationManager.ConnectionStrings ["BSCDB"].ConnectionString;
m_DataAccessLayer = new EAReportingDAL(connectionString);
LoadUserPreferences();
}
protected void Page_Load(object sender, EventArgs e)
{
InitDataAccess();
}
protected void btnSavePref_Click(object sender, EventArgs e)
{
InitDataAccess();
string userName = this.Page.User.Identity.Name;
DataSet availabeData = m_DataAccessLayer.GetUserPreferences(this.Page.User.Identity.Name, Constants.ProjectsUIView);
}

CustomValidator not executing on second step of a multi-panel Page

I am experiencing a problem with an ASPX page not executing a CustomValidator. The Page consists of 3 ASP Panels which swap visibility for each step in a 3 step process. The first step/panel functions as expected, executing all CustomValidators when I click the submit button. If valid, the button click hides its panel and shows the second panel for step #2 which contains another CustomValidator. When clicking the submit button on this second panel, the CustomValidator never executes and the Page always reports that it IsValid.
I have reproduced this behavior in a small, example app. Here is the relevant code...
Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:Panel ID="Panel1" runat="server" Visible="true">
<div>
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBox1"
ValidateEmptyText="true"
Display="Dynamic"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="Type in anything:" AssociatedControlID="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" />
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Show Panel #2" OnClick="Button1_Click" />
</div>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" Visible="false">
<div>
<asp:CustomValidator
ID="CustomValidator2"
runat="server"
Display="Dynamic"
OnServerValidate="CustomValidator2_ServerValidate">
</asp:CustomValidator>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="I should cause an Exception..." OnClick="Button2_Click" />
</div>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" Visible="false">
<p>An exception should have been thrown. :(</p>
</asp:Panel>
</asp:Content>
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = true;
Panel2.Visible = false;
Panel3.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
string userEnteredText = TextBox1.Text;
if (string.IsNullOrEmpty(userEnteredText))
{
CustomValidator1.Text = "Text is required!";
args.IsValid = false;
}
else if (!userEnteredText.ToLower().Equals("anything"))
{
CustomValidator1.Text = "You didn't type 'anything'! ;)";
TextBox1.Text = null;
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
throw new Exception("This ServerValidate() method never triggers!");
}
}
I don't understand why the CustomValidator2 method is never executing. Can anyone explain this behaviour?
As you're not setting the ControlToValidate property in your scenario set the property ValidateWhenEmpty to true on the CustomValidator.
The CustomValidator will not be evaluated when the ControlToValidate is blank unless ValidateWhenEmpty is true.
UPDATE:
Ok this was wrong. But do you really need to set visibility of the panels in the Page_Load? You've done it already declaratively in the .aspx.
If you remove it from Page_Load, the validator works. I suppose it does not work if the validator is Visible=false or is inside a containing control that is Visible=false.
You should use ValidationGroup property of the buttons and the corresponding validation controls in each panel.

How to update a control outside of an updatepanel?

I am going to show some text in a TextBox, which is located outside of an updatepanel, after checking a CheckBox but I cannot make it work. please help me out ?
Here is my code:
<asp:UpdatePanel runat="server" ID="uplMaster">
<ContentTemplate>
<asp:CheckBox ID="cbShowText" runat="server" Text="Show Some Text" AutoPostBack="true"
OnCheckedChanged="cbShowText_CheckedChanged" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox ID="txtBox" Text="Empty" runat="server" />
Code Behind:
protected void cbShowText_CheckedChanged(object sender, EventArgs e)
{
txtBox.Text = "Some Text";
}
Thanks in advance :D
P.S. As you might have guessed, I have resembled my problem and that is why I don't want to put the TextBox in the UpdatePanel
I put the TextBox in another UpdatePanel and then called the Update method:
Here is my new code:
<asp:UpdatePanel runat="server" ID="uplMaster" UpdateMode="Always">
<ContentTemplate>
<asp:CheckBox ID="cbShowText" runat="server" Text="Show Some Text" AutoPostBack="true"
OnCheckedChanged="cbShowText_CheckedChanged" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" ID="uplDetail" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtBox" Text="Empty" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void cbShowText_CheckedChanged(object sender, EventArgs e)
{
txtBox.Text = "Some Text";
uplDetail.Update();
}
Hope this helps
The textbox has to be in update panel also.
*Edit:
I am sorry I didn't read your question properly. Perhaps write a javascript function, and call the function from codebehind?
I know its been a while since this was asked, but here is what I did. Like #bla said write a javascript function and call it from code behind.
So in your checked changed call this. The changeText is a javascript function on your page in the header or in a script file.
protected void cbShowText_CheckedChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "Show Different Text", "changeText();", true);
}
Sample Javascript. Just gets called when checked changed event fires from code behind.
<script type="text/javascript">
function changeText() {
var txt= document.getElementById('<%= txtBox.ClientID %>');
var chk = document.getElementById('<%= cbShowText.ClientID %>');
if (chk.checked === true) {
txt.Text = "Something";
} else {
txt.Text = "Somethingelse";
}
}
</script>
Hope this helps someone.

Resources