sending data from script to .cs page - asp.net

i am getting values from .cs to script but i want to send data from script to .cs page
i have tried this,but it is not working.
<script type="text/javascript">
$(document).ready(function() {
$("hfServerValue").val("From ClientSide!");
});
</script>
<asp:HiddenField ID="hfServerValue" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hfServerValue.Value.ToString ());
}

You can't directly invoke the Page_Load method from script. There are several ways to send data to server.
Try using an XMLHttpReqest
http://www.jibbering.com/2002/4/httprequest.html
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
If you're using jQuery, you may also try $.ajax(), $.load() etc.
Do remember that unlike a submit action which internally creates a request, you're trying to create the request yourself so you might need to deal with stuff like request headers (content-type, content-length etc.), content etc. So, there's a bit of work to do here even though you're trying to do a simple thing. But once you get it running it comes naturally.

You first need to add a control that get the data from javascript and post them back:
<asp:HiddenField ID="hfServerValue" runat="server" />
Then you place data on that control by getting the cliendID.
$(document).ready(function() { $("<%=hfServerValue.ClientID%>").val("From ClientSide!"); });
And then on post back you get them
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
var YourReturn = hfServerValue.Text;
}
}
This is an answer to a question. Of course ajax is a different way.
Update
Now I see the hidden field, this is also a better way the hidden field. The only error is that you did not use the CliendID !. Also I do not know if you use prototype or jquery or just microsoft.

Related

ASP.NET code source updating

I built a website and I want to redirect a site built in asp.net
( similar example www.mysite.net/Front/ContactUs.aspx?Page=ContactUs&mn=ContactUs) to my new site.
the problem is that I have not found where I can make changes in aspx code, I looked into the source code but in vain.
The project contains a lot of files of code, I do not really know what part of the code I have to show you.
Is ASP's projects have a syntax to define the site URLs?
Please I need help, how to make this redirection , and where I can make changes.
Thanks.
Whether you want to redirect all requests or just select individual files, partially or fully, they all normally have a function called Page_Load.
For every file you want to be redirected, you can use this code piece.
private void Page_Load(object sender, EventArgs e)
{
// Check whether the browser remains
// connected to the server.
if (Response.IsClientConnected)
{
// Redirect
Response.Redirect("http://new.website.com/", false);
}
else
{
// Browser is not connected, stop all response processing
Response.End();
}
}
If you want the full site to be redirected, you can use the this function, in global.asax file
<%# Application Language="C#" %>
<script runat="server">
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Response.Redirect("http://new.website.com/", false);
Response.End();
}
</script>

Braintree Drop-In UI in ASP.NET web form with submit button method is not called when clicked

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.

how to prevent refresh on asp.net c# web page button?

how to prevent refresh on asp.net c# web page button?
protected void Button1_Click(object sender, EventArgs e)
{
}
Regards
you must use this way :
<asp:button ID="btn" runat="server" Text="Button" onClientclick="btn_Click(event);"> </asp:button>
<script>
function btn_Click (e)
{
if(//Check somthing)
e.preventDefault();
}
</script>
Short answer, you can't.
However, using methods such as ajax, you can hide the appearance of the postback.
you can do it by creating a cookie inside your Button1_Click method. The first instruction within this method should check if that cookie exists or has not expired. In case itdoesn't exist or it expired, the follow line will create or update the cookie. In case the cookie exists,
return;
Sorry i cant give code cause im using my mobile.

Where to register RegisterClientScriptBlock in ASP.NET?

Where is the best part of asp.net page or code behind to register RegisterClientScriptBlock.
You have a bunch of options.
Register script includes in your <head> section or do inline <script> tags. I prefer to have my scripts at the bottom of the page though.
You can also register it at the Page level in your Page_Load (or any other event) by calling ClientScript.RegisterClientScriptBlock and passing it the script you want. Remember that if you do go with RegisterClientScriptBlock, you will need to make sure that you register the code with every page load so that is why I would recommend the Page_Load event if you want to use this method.
For example:
protected void Page_Load(object sender, EventArgs e)
{
AddClientSideJavascript();
// Do other stuff
}
private void AddClientSideJavascript()
{
// Register some client script code
Type someType = this.GetType();
if (!ClientScript.IsClientScriptBlockRegistered(someType, "TESTSCRIPT"))
{
string script = "function ShowAlert() { alert('Test'); }";
ClientScript.RegisterClientScriptBlock(someType, "TESTSCRIPT", script, true);
}
// Register more here... etc...
}
Just make sure you don't include it the portion of your Page_Load that is wrapped with the if (!IsPostBack) check or else your scripts will not get registered after any postbacks.
The correct answer is - at any point within page_load.

ASP.NET WebForms + Postback then open popup

I have a LinkButton that has to postback to perform some logic.
Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.
So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.
Any other ideas?
Use LinkButton.PostBackUrl to set a different page to POST to, and some client script to get a new window (and the old target restored so that future postbacks work normally). The 2nd page can use PreviousPage to get access to any needed state from the original page.
<script runat="server">
void lnk_Click(object sender, EventArgs e) {
// Do work
}
</script>
<script type="text/javascript">
var oldTarget, oldAction;
function newWindowClick(target) {
var form = document.forms[0];
oldTarget = form.target;
oldAction = form.action;
form.target = target;
window.setTimeout(
"document.forms[0].target=oldTarget;"
+ "document.forms[0].action=oldAction;",
200
);
}
</script>
<asp:LinkButton runat="server" PostBackUrl="Details.aspx" Text="Click Me"
OnClick="lnk_Click"
OnClientClick="newWindowClick('details');" />
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
// Do some server side work
string script = "window.open('http://www.yahoo.com','Yahoo')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"NewWindow",script, true);
}
}
One thing you could try is to have your LinkButton OnClick event do its processing, then register a Page.ClientScript.RegisterStartupScript with the popup code, which will put some Javascript into the tag to fire off after the page loads. This should launch your new window after the processing completes.
EDIT: Reading your comment, I believe you can still use this approach, have your results stored in a session variable, and then have the popup page pull the results from there.

Resources