OnServerValidate Won't work with PostBackUrl in ASP.Net C# - c#

I'm validating a form using a CustomValidator so I can colour the background of the textbox.
The code behind for the CustomValidator doesn't get called when I click the form's linkbutton. However, when I remove PostBackUrl="orderconfirm.aspx" the code does get called and works fine.
aspx page:
<asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName" runat="server">/asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorLN" runat="server"
ControlToValidate="txtBillingLastName"
OnServerValidate="CustomValidatorLN_ServerValidate"
ValidateEmptyText="True">
</asp:CustomValidator>
<asp:LinkButton
ID="OrderButton" runat="server"
PostBackUrl="orderconfirm.aspx"
onclick="OrderButton_Click">
</asp:LinkButton>
code behind:
protected void CustomValidatorLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
bool is_valid = txtBillingLastName.Text != "";
txtBillingLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
args.IsValid = is_valid;
}
I'm pretty new to .net/c# and to be honest I didn't get the answers to similar problems searched for on here.
Any help would be greatly appreciated.

Server side code runs when the page is requested, It doesn't work because you are posting back to(i.e. requesting) a different page, so the code never runs. You could post back to the original page then redirect in the code behind but the easiest solution is probably to eliminate orderconfirm.aspx entirely and just do everything in the original page.

Related

Changing button label from c# code-behind

I am sorry I can't solve what must be simple to everyone else even after reading so many posts. Simply stated... I have an ASP webpage I created in VS2010 and when the user clicks the 'Send Email' button, I want to change the button either using JQuery then calling my code-behind to do the actual send. Alternatively, I want the C# code behind to change the button text while it is in the process of sending so the user knows to hold on.
I am new to JQuery and still pretty new to C#. My website is www. themilwaukeehandcenter.com. If you click the contact us... this is where I want the code. I have tried
$("ContactUsButton").click(function () {
ContactUsLabel.Text = "Processing";
});
on the main page. I have also tried
protected void ContactUsButton_Click(object sender, System.EventArgs e)
{
ContactUsLabel.Text = "Sending... Please Wait";
ContactUsLabel.Refresh();
I know this should be simple but hours later.... reading so many posts later.... I feel no farther. I can't quite figure out how the JQuery onclick and the ASP onclick interact. I also don't know why C# flags the Refresh() as not valid. Any help welcome.
I actually placed a ContactUsLabel on the form too when I couldn't get the ContactUsButton to do what I intended. I am too knew to understand what you mean by 'How have you declared your button, but this is the code that creates it:
<asp:Button ID="ContactUsButton" runat="server"
OnClick="ContactUsButton_Click" Text="Send Email" Width="120px"/>
<asp:Label ID="ContactUsLabel" runat="server" Text="" Width="120px">
</asp:Label>
Your WinForm Code:
<asp:button id="ContactUsButton" runat="server" onclick="ContactUsButton_Click" cssClass="myButton" text="Contact Us" />
On submit use the jQuery script to change button text.
$(document).ready(function() {
$('.myButton').click(function(){
$(this).attr('value', 'Processing...');
});
});
View in fiddler: view
Finally at the server side:
protected void ContactUsButton_Click(object sender, System.EventArgs e)
{
ContactUsButton.Text = "Thank You";
}

How to you code an <a href="... tag in ASPX to call a simple code behind function?

How to you code an <a href="... tag in ASPX to call a simple code behind function?
I have inherited a bit of code. I did not write this originally but I am trying to modify it.
In the steppayment.aspx file there are lots of "<a href..." tags that target either a whole URL or another aspx file.
But what if I only want to call a function in the code-behind, steppayment.aspx.cs?
In the aspx file, steppayment.aspx, I have this line of code:
<u><b><a href="fsModifyVisualContentonPaypal();" >Click here</a></b></u> now to open the PayPal payment window.
In the code behind, steppayment.aspx.cs, I have this line of code:
protected void fsModifyVisualContentonPaypal()
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
I have break points in this function. It never gets here. When the user clicks on the "click here" it throws an error.
Use a LinkButton control instead of a basic HTML anchor tag
<asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server" Text="Click here" />
To call client side methods like javascript you would use OnClientClick. You'll want to check out the documentation for LinkButton on MSDN
If it you want it to work on postback, try an ASP.NET LinkButton control.
This is from memory, but it would be something like this:
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
If you want it to work without a postback, that gets you into either Ajax territory or plain JavaScript. (Or, you might look up the ASP.NET UpdatePanel.)
All of this is assuming that you're using ASP.NET WebForms. If you're using MVC, that's another topic.
Both answers would work. You need to change the event method signature as well like this:
protected void fsModifyVisualContentonPaypal(object sender, EventArgs e)
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
And your link button should look like this ( as suggesested by both answers):
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>

Adding a ASP Control to page from Code Behind within InnerHTML

I'm trying to add a button to the webpage, from the code behind. I have a single empty div on my main page that visible on and off, when needed. However the content I wish to create dynamically as the div content can change dependent on conditions.
I have realised that within my ASP Control I use a / (backslash) which cancels out my HTML. The problem I now have is understanding how I can get around this with code, is there a way to add ASP Controls to the web page? I am open to suggestions outside of the InnerHtml.
I'm creating my Button like so (in my Code Behind):
string buttonout = string.Format("<asp:Button ID=\"helpButton_0\" CommandArgument=\"0\" CssClass=\"HelpButton\" runat=\"server\" Text=\"?\"/>");
innercontent[0] = string.Format("<table><tr><td>Lead Passenger Information</td></tr><tr><td>Here by deafaul we used your detaisl from your profile, if you're not the lead passenger (As in you're booking for someone else) then please change details.</td></tr><tr><td>{0}</td></tr></table>"+ buttonout);
As Said above, The reason this doesn't work is because of InnerHtml hating backslashes, I think.
I do have a solution to this; and that's by adding more divs to the page.
<div id="HelpBoxDiv" runat="server" Visible="false">
<div id="HelpBoxDiv_Top" runat="server" Visible="true">
</div>
<div id="HelpBoxDiv_Bottom" runat="server" Visible="true">
<asp:Button ID="button_HelpBox_false" runat="server" />
</div>
</div>
I would then add my Innerhtml to the _Top Div, instead of the HelpBoxDiv which I am currently doing now. However this solution doesn't teach me anything.
I am hesitant to ask questions here, as I know a lot of question have been asked and I am sure this one has before, but I didn't find a solution. Any help is much appreciated.
Thank you.
I have realised that within my ASP Control I use a / (backslash) which
cancels out my HTML. The problem I now have is understanding how I can
get around this with code, is there a way to add ASP Controls to the
web page? I am open to suggestions outside of the InnerHtml.
You cannot add ASP.Net server control like a literal string.
Instead, you want to add the dynamic server control to the following approach -
ASPX
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
Code Behind
protected void Page_Init(object sender, EventArgs e)
{
var button = new Button
{
ID = "helpButton_0",
CommandArgument = "0",
CssClass = "HelpButton",
Text = "?"
};
button.Command += button_Command;
PlaceHolder1.Controls.Add(button);
}
private void button_Command(object sender, CommandEventArgs e)
{
// Handle dynamic button's command event.
}

ASP.NET Button OnClientClick

I have question and any help will be greatly appreciated. I hope I am explaining this clearly, but if i'm not just let me know, i will be on for a while. This is written in C# and I have a button that calls a javascript function called "JavaScript()" in the "OnClientClick" part and in the "OnClick" part I have an "if statement" where the first part resembles the OnClientClick function and the second part represents different code that is not related to the OnClientClick.
DefaultPage.aspx:
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_OnClick"
OnClientClick="JavaScript()" />
DefaultPage.aspx.cs:
protected void Button1_OnClick(object sender, EventArgs e)
{
String a = getValueofA();
If (a == "1")
{
//OnClientClick code goes here
}
else If (a == "2")
{
//No OnClientClick code goes here
}
}
This javascript function comes from a different Web Control that I am loading on this "DefaultPage". This worked perfect for me until I added the "if statement" in Button1_OnClick. Originally I just had the first part of the "if statement", now I need to add the second part of it. How can I accomplish this. I tried button1.OnClientClick, but it only works in Page_Load. I need to first determine the value of "a" then proceed. Sorry if i'm not clear but i can answer any questions. Thanks so much. My goal is to remove the "OnClientClick=JavaScript" from my asp.net button and just call that function inside the if statement.
What error are you getting? If is not capitalized in C#.
http://msdn.microsoft.com/en-us/library/5011f09h(v=vs.100).aspx
EDIT:
Based on the comments, I think you are better off going client side entirely.
<script type="text/javascript">
function NewFunction(){
var a = getValueOfA();
if (a === "1")
{
JavaScript();
}
else if ( a==="2" )
{
//other code
}
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="NewFunction()" />
I am not sure if I understood your questions, it seems like you want to execute javascript code from the code behind. How about using ScriptManager in the code behind and execute javascript from there? like below
// write your onclientclick code here
ScriptManager.RegisterStartupScript(this, typeof(string), "JAVA_SCRIPT", "your javascript() function code here", true);

Sharepoint Webpart posting data to Application Page via PostBackUrl

I have a Webpart that contains a couple of dropdowns on an update panel. There is a submit button that has the PostBackUrl set to a sharepoint Application Page
<asp:DropDownList ID="ClassSelector" runat="server" Enabled="False"
AutoPostBack="True" onselectedindexchanged="ClassSelector_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-null-">Select Class...</asp:ListItem>
<asp:ListItem Value="1">Class 1</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSubmit" runat="server" Text="Show Page" Enabled="False"
PostBackUrl="~/_layouts/MyWebParts/MyAppPage.aspx" />
This works in redirecting the browser to the Application Page I have created, but I am having trouble accessing the form data.
On the Page_Load function of the Application Page I have the following debugging code.
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
foreach (String s in Page.Request.Form.AllKeys)
{
Label1.Text += s + ": " + Page.Request.Form[s] + "<br />";
}
}
This shows that the data I need has in fact been posted to the page.
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$SemesterSelector: 28
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector: 11-0021-A
But when I try to access this as:
Page.Request.Form["ClassSelector"]
Nothing is returned. I know I must be missing something simple here, but I am not sure what.
Any help is greatly appreciated.
Ah, the ASP.NET master page prefix problem! One of my favorites.
The master page for your application page puts a prefix in front of your server-side controls so that they will be unique. If you end up access your control via the Form collection, you have to access it using not only the control ID, but also the ContentPlaceholder prefix. That's why you see such a large ID dumped out of your debugging logic.
If you want to programmatically get to the ID of the control, you can use FindControl, but you'll have to target the apppropriate content placeholder scope for this. Here's a good tutorial/explanation here (which really emphasizes how complex this can get!).
Of course, the other option you can use is just hard-coding the control id based on what you're seeing from your debugging code...but that won't be reliable if you change content placeholders or more your control to a different container.
I guess the answer depends on how static your controls will be.
Hope this helps. Good luck!!
Well to access it that way you would have to use
Page.Request.Form["ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector"]
As you can actually see from your code where you set the label text to s plus Request.Form[s]

Categories

Resources