C# how to retrieve Stripe Token from the Form.Submit - c#

Can I ask how to retrieve the token from the coding/server side based on this script?
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
Thank you

Here is a basic example of submitting a webform with javascript and accessing the form collection on the server. I have hard-coded the stripe token value, I'm assuming you have that part covered.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication11.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<button onclick="stripeTokenHandler('some token value');">Submit Me</button>
</div>
</form>
</body>
<script>
function stripeTokenHandler(token) {
var form = document.getElementById('form1');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripetoken');
hiddenInput.setAttribute('value', token);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
</html>
Code Behind:
using System;
using System.Diagnostics;
namespace WebApplication11
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//any form inputs can be obtained with Request.Form[]
Debug.WriteLine(Request.Form["stripetoken"]);
}
}
}
}

Related

Trouble calling C# Method from javascript

I read some forums and found an easier way to call a C# Method from JavaScript but it's not working. I did it in my live app and it didn't work so I took a fresh project and used the code as below:
ASPX Mark-up
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="btnMe" runat="server" OnClientClick="jsfun()" />
</div>
</form>
</body>
</html>
Javascript
<script type="text/javascript">
function jdfun() {
PageMethods.CSFun(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onSucess(result) {
alert(result);
}
</script>
C#
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string CSFun()
{
string result = "Hey Yeah";
return result;
}
}
No Error No Exception. The Debugger is not even going into the C# code.
Can anyone help me out.
Thanks.
Edit
I didn't really know about this, but I read a little and fixed your code.
Here is the code that works:
js:
<script type="text/javascript">
function jsfun() {
PageMethods.CSFun(onSuccess, onError);
}
function onSuccess(result) {
alert(result);
}
function onError(result) {
alert(result);
}
</script>
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="Button1" runat="server" OnClientClick="jsfun()" />
</div>
</form>
</body>
</html>
Basic Example to do the same
aspx page
<form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
<fieldset id="ContactFieldset">
<label>
Your Name
<input type="text" id="NameTextBox" /></label>
<label>
Email Address
<input type="text" id="EmailTextBox" /></label>
<label>
Your Message
<textarea id="MessageTextBox"></textarea></label>
<button onclick="SendForm();">
Send</button>
</fieldset>
</form>
Page Method (.cs)
using System;
using System.Web.Services;
public partial class ContactUs : System.Web.UI.Page
{
[WebMethod]
public static void SendForm(string name, string email, string message)
{
if (string.IsNullOrEmpty(name))
{
throw new Exception("You must supply a name.");
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
if (string.IsNullOrEmpty(message))
{
throw new Exception("Please provide a message to send.");
}
// If we get this far we know that they entered enough data, so
// here is where you would send the email or whatever you wanted
// to do :)
}
}
javascript function
function SendForm() {
var name = $get("NameTextBox").value;
var email = $get("EmailTextBox").value;
var message = $get("MessageTextBox").value;
PageMethods.SendForm(name, email, message,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
// Dispaly "thank you."
$get("ContactFieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
// Alert user to the error.
alert(error.get_message());
}

modal dialog not close

RegistrationPage.aspx
function btnSearchClick()
{
if (window.showModalDialog)
{
window.showModalDialog(
"Search.aspx",
"Search Patient",
"dialogWidth:800px; dialogHeight:400px"
);
return false;
}
}
Search.aspx
$(document).ready(function ()
{
$("input[id$='btnAdd']").live('click', function (e) {
hidID.value = $.trim($('table td.csstablelisttdselected:first').text());
return true;
});
});
Seach.aspx.cs
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("RegistrationPage.aspx?ID=" + hidID.Value, true);
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"CloseScript",
"window.close()",
true
);
}
In RegistrationPage.aspx page on click of button search pop up dialog box.
In Search page i am getting id in hiddenfield and redirect to registration page.
When I click on btn add then dialog not close and it redirect to registration page within dialog.
Please dont give answer like "use jquery dialog box","or use another dialog control"
This is a tested example :
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
function btnSearchClick()
{
window.returnValue = undefined;
var result = window.showModalDialog("Search.aspx", window, "dialogHeight:650px; dialogWidth:900px;");
if (result == undefined)
result = window.returnValue;
if (result != null && result != "undefined")
alert(result);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnOpen" onclick="btnSearchClick();" />
</div>
</form>
</body>
</html>
Search.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script>
function CloseModal() {
if (window.opener) {
window.opener.returnValue = 'your return value';
}
window.returnValue = 'your return value';
self.close();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Search.aspx.cs
using System;
using System.Web;
using System.Web.UI;
public partial class Search : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "CloseScript", "closescript()", true);
}
}
So instead of redirect your user you could pass a value from Modal to Opener.
Here another example : Modal Dialog ReturnValue
Hope can help.

get html DIV content from asp.net c# codebehind event

I want to get HTML DIV content via asp.net C# code behind event.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Report.aspx.cs" Inherits="WebApplication1.Report.Report" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#_Hidden_CrystalReportContent').hide();
$('#_Hidden_CrystalReportContent').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="_Hidden_CrystalReportContent">I want to get Current value.</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>
My code behind file as below.
public partial class Report : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void Button1_Click(object sender, EventArgs e)
{
string s = Request["_Hidden_CrystalReportContent"].ToString();
}
}
But I still cannot get div content value.
Please let me get your suggestion.
Make the div runat="server" to access on server.
Html
<div id="_Hidden_CrystalReportContent" runat="server">
Code behind
string htmlOfDiv = _Hidden_CrystalReportContent.innerHTML;
Javascript
$(document).ready(function () {
$('#<% _Hidden_CrystalReportContent.ClientID %>').hide();
$('#<%= _Hidden_CrystalReportContent.ClientID %>').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
Making a div server accessible by puttin runat="server" attribute cause the changed client id if CLientIDMode is not static. You will need to use ClientID attribute to get client id of div in javascript.
Edit: based on comments. You are trying to get the updated html, if so you then you wont get it as on post back only html form elements are posted. Put the changes in some hidden field and assess it on server.
In html
<input type="hidden" id="hdnDivContents" runat="server">
In javascript
$('#<% hdnDivContents.ClientID %>').val("<b>I want to get Current value. 1<sup>st</sup></b>");
In code behind
_Hidden_CrystalReportContent.innerHTML = hdnDivContents.Value;

Call non-static method in server-side from client-side using JavsScript

How do I call a non-static method in server side(aspx.cs) from client side using javascript (aspx)....?
As far as I know I can call static method in server side from client side...
server side:
[WebMethod]
public static void method1()
{
}
client side:
<script language="JavaScript">
function keyUP()
{
PageMethods.method1();
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
It works. Now how do I call non-static method from client side?
You can avoid the static constraint by using a simple .asmx page instead of the codebehind page.
1) Open New Website using the AJAX Enable ASP.NET template (it puts the necessary references in the web.config)
2) SIMPLESERVICE.ASMX - Add a new .asmx web service (I called mine SimpleService.asmx)
Notice the [System.Web.Script.Services.ScriptSerive] decoration and that the SimpleService class implements Webservice.
<%# WebService Language="C#" Class="SimpleService" %>
using System;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public class SimpleService : WebService
{
[WebMethod]
public string GetMessage(string name)
{
return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
}
}
3) DEFAULT.ASPX - To use it reference the service in you script manager and you are off and running. In my Javascript I call the class.method - SimpleService.GetMessage.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function callServer() {
SimpleService.GetMessage($get("Name").value, displayMessageCallback);
}
function displayMessageCallback(result) {
$get("message").innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/SimpleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
</div>
<h1>Hello World Example</h1>
<div>
Enter Name: <input id="Name" type="text" />
Call Server
<div id="message"></div>
</div>
</form>
</body>
</html>
I used the example I found from Scott Gu
Found Here.
No you cannot call non-static methods from client side per se. I've tried it once but it is ugly one (also I used jQuery ajax). Just call the page using ajax with method name appended to it as query string parameter and then on server side check the parameter and call the relevant method. But as I've told you it is pretty ugly :(
$.ajax({'/mypage.aspx?m=mymethod',......}); //this is not correct syntax
on server side:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString.HasKeys() ||
string.IsNullOrEmpty(Request.QueryString["m"]))
{
//return error or something relevant to your code
}
var m = Request.QueryString["m"];
switch(m)
{
case "a":
a();
break;
.....
.....
}
}
Actually, you don't get to call non-static methods in this way.
When you are calling a PageMethod, you're basically calling a special web service. This feature only works with static methods on the same page.
C#
public string LoadString() {
return "my string";
}
JS/jQuery
$('#txt').val(<%= LoadString() %>);
as an answer to Pramulia
i think you want to have a function with an argument from the client side which is implemented in the example -> CallServer(arg1, arg2)
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Implements Interface="System.Web.UI.ICallbackEventHandler" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>Client Callbacks</title>
<script runat="server">
public void RaiseCallbackEvent(String eventArgument)
{
// Processes a callback event on the server using the event
// argument from the client.
}
public string GetCallbackResult()
{
// Returns the results of a callback event to the client.
string dateString = DateTime.Now.ToLongDateString();
return dateString;
}
void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
</script>
<script type="text/javascript">
function ReceiveServerData(arg, context) {
Message.innerText = "Date from server: " + arg;
}
</script>
</head>
<body>
<h2>Client Callbacks Without Postbacks</h2>
<form id="form1" runat="server">
<input type="button" value="Callback"
onclick="CallServer('1', alert('Callback sent to Server'))" />
<br />
<span id="Message"></span>
</form>
</body>
</html>
If you want to call it using the same function, you can use the following code:
[WebMethod]
public static void method1()
{
ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
obj.yourFunctionName(ParametersIfAny);
}
I ended up using hidden fields in case anyone reads this. I can set the value in c# under a function and then read it in javascript.
Dave has written in detail about calling page methods from client side using jquery ajax. The general idea is like this (if you find any problem please refer to Dave's site).
C# Code:
[WebMethod]
public static string yourmethod(/*params*/)
{
return "Hello World!"
}
ASPX:
$.ajax({
type: 'POST',
data: /*Your Data*/,
dataType: 'JSON',
contentType: 'application/json',
url: '/yourpage.aspx/yourmethod',//Method to call
success: function(result, status) {
//handle return data
},
error: function(xhr, status, error) {
//handle error
}
});

Asp.Net Static method to refresh page

I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text.
What I was wanting to do, is if a certain condition is met, to refresh the page completely.
Am I going to be able to do this in the current method that I have? here's my current stuff:
ASP.NET
<cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server"
ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1"
ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" />
Javascript
Sys.Application.add_load(function(){updateQueue();});
function updateQueue()
{
var queueShown = document.getElementById('<%= hiddenFieldQueueShown.ClientID %>').value;
if(queueShown == 1)
{
var behavior = $find('dp1');
if (behavior)
{
behavior.populate();
setTimeout('updateQueue()', 5000);
}
}
}
SERVER (C#)
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetQueueTable()
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
try
{
// do stuff
}
catch (Exception ex)
{
// do stuff
}
return builder.ToString();
}
You can't do anything from your ASMX.
You can refresh the page from JavaScript by using a conventional page reload or by doing a postback that would perform server-side changes and then update via your UpdatePanel or, more simply, a Response.Redirect.
You can force a Postback from Javascript, see this Default.aspx page for a example:
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function forcePostback()
{
<%=getPostBackJavascriptCode()%>;
}
</script>
</head>
<body onload="javascript:forcePostback()">
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Postbacking right now..."></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.cs
namespace ForcingApostback
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) Label1.Text = "Done postbacking!!!";
}
protected string getPostBackJavascriptCode()
{
return ClientScript.GetPostBackEventReference(this, null);
}
}
}
On the client-side, under any condition, you could then call the forcePostback() Javascript function to force the Postback.

Categories

Resources