Why isn't my code-behind working properly? - asp.net

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

Related

button enable not working on code behind on aspx page

Here is my aspx code for button
<div id="navigationButtons">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" CssClass="button submit" Enabled="true" />
<asp:Button ID="btnNext" name="btnNext" Text="NEXT" ToolTip="Next" runat="server" CssClass="button next" TabIndex="0" OnClick="btnNext_Click" Enabled="false"/>
<asp:Button ID="btnPrev" Text="PREV" ToolTip="Previous" runat="server" CssClass="button prev" TabIndex="2" OnClick="btnPrev_Click" Enabled="true"/>
<asp:Button ID="btnExit" Text="EXIT" ToolTip="Exit" runat="server" CssClass="button exit" TabIndex="3" OnClick="btnExit_Click" />
</div>
here is my code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
string selectedAnswers = presentationManager.GetSelectedAnswer(pnlQuestionOptions);
if (!String.IsNullOrEmpty(selectedAnswers))
{
questAnsInfo = new QuestionAnswerInfo();
questAnsInfo = persistanceManager.GetPersistanceDataForModification();
questAnsInfo.Answer = selectedAnswers;
Question question = persistanceManager.GetQuestionData(presentationManager.GetCourse().Title, Convert.ToInt32(questAnsInfo.Index));
string feedBack = presentationManager.GetFeedBack(question, selectedAnswers);
lblFeedback.Text = feedBack;
feedbackPanel.Visible = feedBack== string.Empty ? false : true;
questAnsInfo.Weight = presentationManager.GetWeight(question, selectedAnswers);
if (persistanceManager.ModifyToPersistance(questAnsInfo))
{
}
btnSubmit.Enabled = false; //not working
btnNext.Enabled = true; //not woriking
}
}
In above webform code behind I have set the property of the buttons accordingly. But there is no change in property in aspx page. What should I do to make it work?
try this: i think this will work...
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
btnSubmit.disabled= true;
btnNext.disabled= false;
}
or you can also try:
btnSubmit.Attributes["disabled"] = "disabled";
hope this will help you.
Actually the update panel was not working in my case. I have placed my buttons inside update panel and now it has worked.
Thanks for answering.
These responses are all very helpful! I found success by putting asp:button in an update panel - but ONLY after calling the [updatepanelcontrol].update() method. Important detail.

Modal ASP.net user control

I have a web form app where a couple of user-controls have been developed and placed on a page where a customer is building an order. The user-controls are pretty extensive in what they do, causing post-backs, etc.
I'd like to display them in a modal fashion without putting them in a separate page (if possible). So therein lies my question.
Is it possible to place user-controls within divs/panels, display them modally and keep them displayed modally (even through postbacks) until the user clicks a button on the control to dismiss it?
I'm basically looking at the modal option because I need to disable the rest of the form while the user is dealing with the sections the user-control is on. So I'm looking for a best-practice approach I suppose and some nudges in the right direction for this.
Thanks!
ADDITION:
I wanted to update this with the code I wrote in hopes that it might help somebody else and also if there is a better way to implement this, then I'm all ears too.
The basics of this is that I'm passing everything back and forth between my user control and the container page through session vars. I use this to tell the container page whether or not the user control is "finished" and until the flag is set to true, the container page just keeps re-displaying the user control modally on each postback. Seems to work well so far.
Markup:
<%# Register Src="../controls/mylabel.ascx" TagName="mylabel" TagPrefix="uc1" %>
<div style="width: 100%;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to cart" OnClick="ButtonAddToCartClick" />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlOutput" Visible="False" runat="server" Width="500px">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<div style="visibility: hidden;">
<asp:Button ID="ButtonHidden" runat="server" Text="Button" />
</div>
<asp:Panel ID="pnlDownload" Visible="False" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div style="width: 100%;">
<uc1:mylabel ID="mylabel1" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
Code behind:
protected void Page_PreRender(object sender, EventArgs e)
{
InitializeControls();
}
protected void Page_Load(object sender, EventArgs e)
{
InitializeControls();
}
private void InitializeControls()
{
DisplayDownloadPanel(!SessionDownloadComplete);
if (SessionDownloadItemNumber != string.Empty)
{
Label1.Text = SessionDownloadItemNumber != "CANCEL" ? "Item ordered from control was: [" + SessionDownloadItemNumber + "]" : "Order was canceled.";
pnlOutput.Visible = true;
}
}
protected void ButtonAddToCartClick(object sender, EventArgs e)
{
bool haveWeSomeText = string.IsNullOrEmpty(TextBox1.Text) == false;
if (haveWeSomeText == true)
{
SessionDownloadComplete = false;
DisplayDownloadPanel(true);
}
}
private void DisplayDownloadPanel(bool show)
{
pnlDownload.Visible = show;
if (show == true)
{
ModalPopupExtender1.Show();
}
else
{
ModalPopupExtender1.Hide();
}
}
private string SessionDownloadItemNumber
{
get { return Session["DownloadItemNumber"] != null ? Session["DownloadItemNumber"].ToString() : string.Empty; }
}
private bool SessionDownloadComplete
{
get { return Session["DownloadComplete"] == null || Convert.ToBoolean(Session["DownloadComplete"]); }
set { Session["DownloadComplete"] = value; }
}
Have a look at ASP.NET Ajax Toolkit Modal popup extender
Take a look at the jQuery UI dialog.
It is a good solution for cross browser modal dialogs in the browser.
<script>
$(function() {
$( ".dialogClass" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
There are a few initial hiccups integrating it with asp.net. But all those are very well documented here on stackover flow itself.

how to disable server side validation on asp.net web forms from browser?

I wanted to disable asp.net validation server controls from browser. I checked online but did not find any way to disable the server side validation; it can be disabled only on the client side using JS/jQuery.
Here is the scenario: I have a checkbox and selecting which displays a set of text boxes. Only if the checkbox is checked, required field validator should fire for the text boxes. I don't want to call a postback on checkbox. Actually those chceck boxes will be generated with jQuery templating so postback is not an option to enable disable validtion.
I would like to know whether there is any way we can enable disable the .CausesValidation property for the controls from browser using some setting? Or is there a way to capture the controls which are to be considered for validation slectively in some event before page_load?
[Update]
Based on Accepted answer, here is my solution:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" ControlToValidate="textbox1" runat="server"
ErrorMessage="enter text"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" ControlToValidate="textbox2" runat="server"
ErrorMessage="enter text for 2"></asp:RequiredFieldValidator>
<asp:CheckBox ID="check1" runat="server" Text="choose" />
<asp:Button ID="submitBtn" runat="server" OnClick="submitBtn_Click" Text="submit" />
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:ValidationSummary ID="summary" runat="server" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
req1.Enabled = false;
req2.Enabled = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
Response.Write("valid form");
}
else
{
Response.Write("invalid form");
}
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (check1.Checked)
{
req1.Enabled = true;
req1.Validate();
}
}
The solution for me would be to use a CustomValidator with a OnServerValidate method.
In the OnServerValidate method I would check if the checkbox is checked, in that case I would verify if the textboxes are filled. It is not necessary to do any change in the CausesValidation property.
The only condition is not to include the property "ControlToValidate". A CustomValidator does not fire if the textbox is empty that's why.
So the code would be like this:
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="prueba" />
<asp:CheckBox ID="chb" runat="server" Text="Check" />
<asp:TextBox ID="txbBox" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:Button ID="btn" runat="server" Text="Prueba" />
And the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Page.Validate();
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (chb.Checked)
{
if (txbBox.Text == String.Empty)
{
cvBox.IsValid = false;
}
}
}

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.

ASP.Net: Ajax registration question

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

Resources