The problem looks very simple but it giving me pain
i am making a login page manually which checks for user email and password from linq. on login page there is an asp label which shows the error msg based on query result like "user not exist" or "user is inactive" etc. there are asp required field validators on both text boxes.
the problem is if user first attempt get unsuccessful and message get displayed on lable, it do't go away unless user get successfully loged in. i want the text back as lable1.text="" on submit button but it can't as its a server side control and the text box validators do't let it go if empty. do i have to use java script?
The easiest thing to do here would be to clear the messages in javascript, as you thought.
<asp:Button ID="SubmitButton" OnClientClick="ClearLableText" runat="server" />
And updated javascript, per your comment:
function ClearLableText() { var element = document.getElementById("<% this.lblMessage.ClientID %>"); element.innerHTML = ""; }
You can try this
protected void page_load(object sender, EventArgs e)
{
MyMessageLabel.Text = ""; //or .Visible = false;
}
protected void Button_Click(object sender, EventArgs e)
{
//By this time, page_load had already executed and the Message Label cleared
MyMessageLabel.Text = "new result from server";
if(validResult)
//RedirectToWhere();
else
//StayOnPage();
}
Hope it works for you.
Related
I have created a simple payment form where contains fields that accept amount, the drop-in UI and the submit button.
<form id="form1" runat="server">
<div>
<label>Amount:</label>
<asp:TextBox ID="txtAmount" runat="server" />
</div>
<div id="dropin-container"></div>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
braintree.setup("<%= this.ClientToken %>", "dropin", { container: "dropin-container" });
</script>
and the code behind
protected string ClientToken = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GenerateClientToken();
}
}
protected void GenerateClientToken()
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "merchant-id",
PublicKey = "public-key",
PrivateKey = "private-key"
};
this.ClientToken = gateway.ClientToken.generate();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "merchant-id",
PublicKey = "public-key",
PrivateKey = "private-key"
};
var request = new TransactionRequest
{
Amount = Convert.ToDecimal(this.txtAmount.Text),
PaymentMethodNonce = Request.Form["payment_method_nonce"]
};
Result<Transaction> result = gateway.Transaction.Sale(request);
}
After I load the page in the browser, I can see the form that accept amount and also the drop-in ui form which accept credit card and/or PayPal.
The issue is when I click Submit button, the method btnSubmit_Click doesn't get called. The page looks like it post back correctly but I cannot see any line of code within the btnSubmit_Click is executed.
I follow the instruction from this page:
https://www.braintreepayments.com/features/drop-in
But I really can't think of anything that I miss.
Anyone can help me with this issue would be very appreciated. Thank you so much.
Knott
I work at Braintree and can help you with this question.
Some background on what braintree.js is doing when you load the Drop-in on your page: it listens for form submissions, and when it detects one it will interrupt the form submit, communicate with Braintree to generate a nonce, and then run your callback if defined. What’s happening is that your .NET postback event is broadcasting a submit action – the same type of action that braintree.js interrupts in the first place.
As a workaround, you can try adding the following to your Page_Load code:
ClientScript.GetPostBackEventReference(this, string.Empty);
ClientScript.RegisterClientScriptBlock(this.GetType(), "PayEvent","<script>function PayEvent() {document.getElementById('__EVENTTARGET').value = '"+ btnSubmit.ClientID +"'; }</script>" );
btnSubmit.Attributes.Add("onClick", "PayEvent()");
Where btnSubmit is the ID of your button.
This should circumvent the submit interruption and allow your form to be submitted properly. In addition, this problem does not occur with our custom integration as an alternative.
Let us know if you have any further questions.
You just needed to put your transaction request code in a method and then call that sub on a post back rather than page load.
This way the auto submit won't interrupt with things.
Protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
GetClientToken();
} else {
Pay();
}
}
protected void Pay() {
PaymentMethodNonce = Request.Form["payment_method_nonce"]
//Build request string etc.
}
Brian,
Your solution above was supplied to me by PayPal support, but unfortunately, it doesn't solve the problem.
To be honest, it is this 'listening' (read: unreliable, 'clever code') to form submissions which is causing all the problems when one tries to integrate it in a Web Forms/UpdatePanel page - it really isn't designed for WebForms/UpdatePanels and requires all kinds of really messy code to make it work and synchronise properly. It is almost as if it was never designed for anything other than MVC or Java!
What would be a far better solution would be if we could attach a JavaScript call in OnClientClick of a button which synchronously calls BrainTree/PayPal via a JavaScript module hosted on PayPal which returns the nonce so that we can then do something with it. As it stands now, the Braintree/PayPal code intercepts a submit button (all buttons in WebForms are 'submits' by default, so this causes problems) and fires off a call asynchronously to get a nonce and at the same time, calls the button OnClick in the C# code. The net result is that the C# code runs before the Braintree/PayPal call returns and you can never synchronise the two.
I have an asp.net button in my page, after I click the button, it is clicked again and again whenever I refresh the same page.
I tried;
if (!IsPostBack)
{
.....
}
for the click function of the button, but in this case button is not working.
<asp:Button ID="btnCommentSubmit" runat="server" Text="Submit" CssClass="leaveAComment" onclick="btnCommentSubmit_Click" />
above is the button.
protected void btnCommentSubmit_Click(object sender, EventArgs e)
{
string cityID = BusinessClass.Default.findCityIDByCountryAndCityName(Request.QueryString["city"].ToString(), "url").ToString();
BusinessClass.Default.makeComment(txtComment.Text, Session["userID"].ToString(), cityID);
txtComment.Text = null;
}
and this is the function.
If don't get you wrong your problem is when you hit F5 after clicking the button. Trying to resubmit the form is the normal behavior and is not related to asp.net but to browsers in general.
F5 causes to re-execute last request to the server, in your case, a POST request.
A way to avoid this issue is implementing the web pattern Post/Redirect/Get
Easy fix with a bit of JavaScript.
document.onkeydown = function() {
if(event.keyCode==116) {
event.keyCode=0;
event.returnValue = false;
}
}
This would stop the duplicate resend when you hit F5.
I am very surprised to see last night my code was working fine and the next day suddenly my textbox.text always have empty string..
My code is:
Name of Event* :
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Code behind:
protected void Page_Load(object sender, EventArgs e) {
}
protected void create_Click(object sender, EventArgs e) {
if (!object.Equals(Session["UserLoginId"], null)) {
int mid = 0;
int cid = 0;
bool valid = true;
if (this.TextBox1.Text == "") {
error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
}
else {
.... // database insert ....
}
I am always ending up with an error.text value.
Why?
Had a similar problem with text boxes getting cleared on adding a new row. It was the issue of the page reloading when the add button was clicked.
Fixed the issue by adding:
Sub Page_Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Per Microsoft's documentation http://msdn.microsoft.com/en-us/library/aa478966.aspx.
Kinda mentioned but you should make sure your checking your that Post_Back event is not clearing your textbox. It would by default.
Try something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.TextBox1.Text == "")
{
error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
}
else
{
//.....
}
}
}
I had a similar problem. I had a textarea feeding data to a database on postback. I also designed the page to populate the textarea from the same database field. The reason it failed was because I forgot to put my reload logic inside an if(!IsPostPack) {} block. When a post back occurs the page load event gets fired again and my reload logic blanked the textarea before I could record the initial value.
If the page make a post back, then all the data , the user entered ,will be erased,as the controls are stateless, so u should keep your data entry through EnableViewState = true.
I am having this issue, but i'm using Telerik Ajax request with target in javascript. I have a RadTextBox and a RadButton. I call the same code from both of them but if i call it from the textBox and request a postback, the textbox is empty in the page load. So i call RadAjaxManager.ajaxRequestWithTarget('someUserControlClientID', 'myTextBoxText');
So in the page_load, i can grab the text, in case it's not sent to the server with the arguments sent, Request.Form("__EVENTARGUMENT") will hold my textBox value.
by the way, RadAjaxManager.ajaxRequestWithTarget is like __doPostBack('targetID', 'arguments');. Hope this helps someone. I don't have time to investigate why i lose the text with this request, so this is the workaround i did.
I'm starting in asp.net and am having some problems that I do not understand. The problem is this, I am building a site for news. Every news has a title and body. I have a page where I can insert news, this page uses a textbox for each of the fields (title and body), after clicking the submit button everything goes ok and saves the values in the database. And o have another page where I can read the news, I use labels for each of the camps, these labels are defined in the Page_Load. Now I'm having problems on the page where I can edit the news. I am loading two textboxes (title and body) in the Page_Load, so far so good, but then when I change the text and I click the submit button, it ignores the changes that I made in the text and saves the text loaded in Page_Load.
This code doesn't show any database connection but you can understand what i'm talking about.
protected void Page_Load(object sender, EventArgs e)
{
textboxTitle.Text = "This is the title of the news";
textboxBody.Text = "This is the body of the news ";
}
I load the page, make the changes in the text , and then click submit.
protected void btnSubmit_Click(object sender, EventArgs e)
{
String title = textboxTitle.Text;
String body = textboxBody.Text;
Response.Write("Title: " + title + " || ");
Response.Write("Body: " + body );
}
Nothing happens, the text in the textboxes is always the one I loaded in the page_load, how do I update the Text in the textboxes?
Page_Load runs every time your page is requested. If you're doing a one-time setup operation to populate the textboxes, don't repopulate them on every request.
You can do that by checking the IsPostBack flag to only execute the initialization code once.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
textboxTitle.Text = "This is the title of the news";
textboxBody.Text = "This is the body of the news ";
}
}
Sounds like you need to check the IsPostBack variable like so:
if(!Page.IsPostBack)
{
textboxTitle.Text = "This is the title of the news";
textboxBody.Text = "This is the body of the news ";
}
That way, you only set te text of the controls on the first page request. Alternately, you can just specify this text on the HTML control itself, without using code in the .cs.
I have a textbox and a button on the ascx page.
After entering text i click on the button where it will post to the database and clear the textbox.
After positing, if i refresh the web page it is going to the button click method and posting the old text to the database. how can i clear the textbox value from the view state.
i have set the enableviewstate of the textbox to false. But still it is not working. Please let me know. Thanks
protected void Button_Click(object sender, EventArgs e)
{
var txt=textBox1.Text;
textBox1.Text="";//Set it to empty
// do other stuff
............
............
}
protected void btnClear_Click(object sender, EventArgs e)
{
ClearControls();
}
private void ClearControls()
{
foreach (Control c in Page.Controls)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Text = string.Empty;
}
}
}
}
After you save your data with the click button you can set the textbox.text = ""
EDIT: After your comment that textbox.text = "" is not working....
When you hit the refresh it sounds like it is resubmitting your work again. Try just reloading the page by browsing to your page again.
Also be sure to check that you aren't saving your data on every postback but just on the button click event.
Do you have any code in your page load event?
Long shot here, but this worked in my case:
TextBox.Attributes.Remove("value");
This was on a textbox with the text mode sent to 'Password'.
just add this at the end of the event after page i going o be refresh
Response.Redirect("Registration.aspx");
here my WebForm name is "Registration.aspx" instead of this put your WebForm name.