Send info to code behind without postback - c#

First, I'm a student, though this is not for school. I'm trying to create a contact us page for my church's website (http://fpcoakwood.azurewebsites.net). I haven't published the contact page yet, as I'm trying to build it. I'm using Bootstrap/jQuery/ASP.NET to build the site. There is a videos page that uses ASP to get the list of videos from YouTube for our channel, and then populates the select html element from that, and I have it working so that selecting a different video loads that video into the player without a postback (though I do wish I could make the back button take me back to the prior page, rather than cycling through prior videos first).
On this page, my challenge is that I'm trying to send an email. I have the code behind working so that I can send the email, but I'm also trying to disable the send button and fadeIn a result div, which would show either success or failure to send the email. The problem is that because the postback occurs, the page reloads, and I lose the disabling of the button and the showing of the status.
Here's some of the code I have so far:
HTML:
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" OnClick="sendMail_Click" OnClientClick="sendMail(); return false;" runat="server" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Success!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later.</div>
JS:
$("#sendMail").click(function (event) {
event.preventDefault();
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").attr("disabled", true);
$("#sendMail").attr("text", "Sending...");
return true;
});
C#:
protected void sendMail_Click(object sender, EventArgs e)
{
//sendMail.Enabled = false;
//sendMail.Text = "Sending...";
SendMessage();
}
If I get rid of the javascript function, I can send the email. It goes through no problems. But with the javascript function, the breakpoint in the C# function is never hit, so it's not hitting the server. What I want is to be able to validate in js before sending to the server, then send to the server without a postback, and have the server send a message to the js allowing either the fail or the success message div to fadeIn().
Any help will be VERY much appreciated. Thanks in advance!

The jquery function runs before the C# code behind and interfere with it's result.
To do what you want you could do all the work on the server-side.
You can use ajax to do that.
Use an updatepanel around the controls and an updateprogress with the "sending..." message. Capture the sendmessage() result and then show the #sendsuccess or #sendFailed according to it.

I ended up using the answer in this post (How to call code behind method from a javascript function?) to do what I wanted to do. Surely it could have been done with Filipe's answer, but at this point, I'm already drinking from a fire hose trying to learn what I can learn, so this was easier for me, since I already have a fair understanding of all of the pieces involved.
Here's my HTML:
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div class="col-md-8 col-md-offset-2" runat="server">
<div class="form-group">
<label for="userName">Your name (requrired):</label>
<input type="text" class="form-control" id="userName" runat="server" />
</div>
<div class="form-group">
<label for="email">Email address (required):</label>
<input type="email" class="form-control" id="email" runat="server" />
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" id="message" rows="5" runat="server"></textarea>
</div>
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" runat="server" OnClientClick="sendMail(); return false;" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Your message has been sent. Thank you for contacting First Pentecostal Church of Oakwood. You are important to us!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later. You are important to us!</div>
</div>
</form>
There is an error in the HTML, as the OnClientClick doesn't find the function, but without it and the return false, the page does a postback. I'm not sure how to fix it, as the preventDefault() in the JS doesn't solve it, and using the UseSubmitBehavior by itself doesn't do it, either. But this works, though it shows as an error in the developer tools in the browser.
Here's the CSS:
#sendSuccess,
#sendFailed {
display:none;
border: 1px solid black;
border-radius: 5px;
padding: 5px;
}
#sendSuccess {
background-color: rgba(147, 197, 75, .7);
}
#sendFailed {
background-color: rgba(201, 48, 44, .7);
}
Here's the JavaScript:
//Set up event handler for send message contact page button
$("#sendMail").click(function (event) {
event.preventDefault();
sendMail();
});
//above is in the $(document).ready function
function sendMail() {
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").prop("value", "Sending...");
$("#sendMail").attr("disabled", true);
var name = $("#userName").val();
var email = $("#email").val();
var msg = $("#message").val();
PageMethods.SendMessage(name, email, msg, onSuccess, onError);
}
function onSuccess(result) {
if (result) {
$("#sendSuccess").fadeIn();
$("#userName").prop("value", "");
$("#email").prop("value", "");
$("#message").prop("value", "");
$("#sendMail").prop("value", "Send Message");
$("#sendMail").attr("disabled", false);
}
else { onError(result); }
}
function onError(result) {
$("#sendFailed").fadeIn();
$("#sendMail").prop("value", "Try Again");
$("#sendMail").attr("disabled", false);
}
And here's the C#:
[System.Web.Services.WebMethod()]
public static bool SendMessage(string user, string email, string msg)
{
string to = "xxxxxxxxx#outlook.com";
string from = "xxxxxxxxxx#outlook.com";
string subject = "Message from OakwoodFPC.org Contact Page";
string body = "From: " + user + "\n";
body += "Email: " + email + "\n";
body += msg;
MailMessage o = new MailMessage(from, to, subject, body);
NetworkCredential cred = new NetworkCredential("xxxxxxxxxx#outlook.com", "password");
SmtpClient smtp = new SmtpClient("smtp.live.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = cred;
try
{
smtp.Send(o);
return true;
}
catch (Exception)
{
return false;
}
}

Related

Add/Remove Class Using Jquery (In View Or Code Behind)

I have an asp.net webfore application which on the page i have an accordion and in that it has some fields. On the first asp:textbox it has an onclick as it checks my db to see if the user exists or not. If they do an asp:Label is then displayed.
The issue i have is that when ever i click outside or tab out this field my accordion closes and i need it to stay open. I was think though is is possible to do this via JQuery even though my field has the onclick or do i need to add it to my code behind?
In my view i tried
$("#MainContent_txtRemoveUser").on("blur", function ()
{
if ($('#MainContent_txtRemoveUser').val() != '')
{
$('panel-collapse collapse').removeClass('collapse');
$(this).addClass('in');
}
});
but it doesn't work
In my code behind i tried
#region Checks if user exists in 'Users' db when field clicked out of
protected void txtRemoveUser_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtRemoveUser.Text))
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT 1 FROM Users WHERE Name = #Name", conn);
cmd.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
removeUserNotExist.Visible = false;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>function endRequestHandler(sender, args){$('#collapseOne').collapse.in()};</script>", false);
}
else
{
removeUserNotExist.Visible = true;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>function endRequestHandler(sender, args){$('#collapseOne').collapse.in()};</script>", false);
}
}
}
#endregion
but this too doesn't work
The HTML of my accordion is
<div id="RemoveUser" class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="accordion-toggle collapsed">Remove Users From The List</a>
</h3>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<p>If you would like to remove yourself or someone else from the list, please populate all the fields below ensuring to enter the <b>FULL</b> name of the user (whether its you or another user) and then click the 'Remove From List' button.</p>
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist. Please try again." Visible="false" style="color: red"></asp:Label>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
</div>
</div>
<div class="row">
<div class="col-sm-offset-8 col-sm-3" style="padding-left: 0px">
<asp:Button runat="server" ID="btnRemoveUser" Text="Remove From List" CssClass="btn btn-danger" data-toggle="modal" data-target="#removeUserModal" data-backdrop="static" data-keyboard="false" ToolTip="Click to remove the specified user from the payday lunch list." />
</div>
</div>
</div>
</div>
</div>
</div>
None of these appear to work. I may be completly wrong in what i have done though.
The state of the accordion is getting lost on postback (which gets triggered on the textbox's text change event). One way to handle this is to maintain the value in a hidden field and then use this value to reset the accordion.
In .aspx add
<asp:HiddenField runat="server" ID="SetAccVisible" />
Then the corresponding javascript changes to:
$('document').ready(function () {
var hdnFldId = '<%= SetAccVisible.ClientID %>';
$("#txtRemoveUser").on("blur", function () {
//Set value of hidden field to show panel after postback
$('#' + hdnFldId).val(true);
});
if ($('#' + hdnFldId).val() == 'true') {
showPanel();
//lets reset the value
$('#' + hdnFldId).val(false);
}
function showPanel() {
if ($('#MainContent_txtRemoveUser').val() != '') {
$('.panel-collapse').removeClass('collapse').addClass('in');
}
}
});
You are missing class selector to target element. It should be:
$('.panel-collapse.collapse').removeClass('collapse');
In your Jquery, you have a little problem with your selector :
$("#MainContent_txtRemoveUser").on("blur", function ()
{
if ($('#MainContent_txtRemoveUser').val() != '')
{
$('.panel-collapse .collapse').removeClass('collapse');
$(this).addClass('in');
}
});
You forget the point before the class selector ;)
You can read more about JQuery selector here =>
https://api.jquery.com/class-selector/
Also, you can optimize your Jquery code :
$("#MainContent_txtRemoveUser").on("blur", function ()
{
if ($(this).val()) // == if $(#MainContent_txtRemoveUser).val() != ""
{
$('.panel-collapse .collapse').removeClass('collapse');
$(this).addClass('in');
}
});
You check the value of the selector's function (#MainContent_txtRemoveUser")
You can use the '$(this)' selector for call it again, in the function. ^^
And, don't forgot you can use a breakpoint in your browser for check your javascript!
Hope I help you :p

ASP.Net Modal Not Displaying

I have an ASP.Net form which on when a 'Submit' button is clicked it sends an email. This can take some time so i wanted to add a processing modal to the user knows that something is happening.
Now i have the modal displaying BUT it only displays once the email has either been sent of failed. I need this modal to be displayed as soon as the button is clicked and then close once the email action has either sent it or failed the send it.
If it fails my page do currently display an error message.
My HTML is
<div class="form-group">
<div class="col-xs-12">
<div class="pull-right">
<asp:LinkButton ID="pg3button" runat="server" OnClick="pg3button_Click" CssClass="btn btn-primary"><span aria-hidden="true" class="glyphicon glyphicon-ok"></span> Send & complete</asp:LinkButton>
</div>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<asp:Label ID="lblModalTitle" runat="server" Text="">Processing</asp:Label>
</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblModalBody" runat="server" Text="">
<p class="text-center">IMAGE GOES HERE</p>
</asp:Label>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
My code behind for my onclick for the submit button is
protected void pg3button_Click(object sender, EventArgs e)
{
try
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("test#test.co.uk");
//Configure the address we are sending the mail from
MailAddress address = new MailAddress("test#test.co.uk");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = "Enquiry";
msg.Body = Label1.Text + " " + Session["pg1input"].ToString()
+ Environment.NewLine.ToString() +
Label2.Text + " " + Session["pg1dd"].ToString()
+ Environment.NewLine.ToString() +
Label3.Text + " " + Session["pg2"].ToString();
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //only enable this if your provider requires it
//Setup credentials to login to our sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("test#test.co.uk", "Password10");
client.Credentials = credentials;
//MODAL CODE TO GO HERE
//Send the msg
client.Send(msg);
Response.Redirect("/Session/pg4.aspx");
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "<div class=\"form-group\">" + "<div class=\"col-xs-12\">" + "There was a problem sending your request. Please try again." + "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-xs-12\">" + "If the error persists, please contact us." + "</div>" + "</div>";
}
}
I have also tried moving the follwing code outside my try
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
I was think if there was a way i could call my button click then a function which has my email code in it but im new to ASP.Net and webforms
All i need is for the modal to be displayed the minute the button is clicked and removed once the page either redirects (if successful) or when my error is displayed
just use JavaScript instead of server side code for modal popup
when you click on button add OnClinetClick event and use a javascript function like
<asp:button id="pg3button" runat="server" OnClick="pg3button_Click" OnClientclick="ShowPopup();"></asp:button>
<script>
function ShowPopup()
{
$('#myModal').modal();
}
<script>
also remove update panel it is not useful in this context.
You are registering your script which shows modal,using the reigisterStartupScript function. Since it is a script it will get registered on the page only after the execution of your c# code. Try moving it to the aspx page itself on the onClientClick event of the button.
$( "#buttonId" ).click(function() {
$('#myModal').modal();
});

Webmail confirmation without new page

I have used this method: http://www.asp.net/web-pages/overview/getting-started/11-adding-email-to-your-web-site
to allow website users to submit Name and Email.
Using this method I have a simple form on one page, which then opens a new page to process the form, sends the email and returns a success message. This works fine in itself, but I would prefer to avoid opening the new page for processing.
(I tried putting all the code on the start page, but then it sends a mail whenever the page loads)
I would much prefer to either replace the form's div with the success message, or pop up a modal with the success message, but I'm not sure how to go about doing this.
I tried putting the processing code in a modal (bootstrap 3), but I don't know how to pass the variables (user input) to the modal (modal being in a separate file to avoid the aforementioned sending on page load behavior)
The processing page (ProcessRequest.cshtml) is as follows:
#{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var sub = Request["sub"];
var errorMessage = "";
var debuggingFlag = false;
try
{
// Send email
WebMail.Send(to: "email#hotmail.com",
subject: "Form submitted on HMD. Name: " + customerName + " Email: " + customerEmail,
body: "Submitted details: " + Environment.NewLine + "Name: " + customerName + Environment.NewLine + "Email: " + customerEmail + Environment.NewLine + "Subscribe: " + sub, isBodyHtml: false
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
}
<p>Thankyou for submitting your email, <b>#customerName</b>.
Back
And the form itself is as follows:
<form class="form-inline" method="post" action="~/ProcessRequest.cshtml">
<div class="form-group col-xs-9">
<input type="text" placeholder="Name" name="customerName" class="form-control txt-primary clearable" />
</div>
<div class="form-group col-xs-9">
<input type="email" placeholder="e-mail" id="customerEmail" name="customerEmail" class="form-control txt-primary clearable" />
</div>
<button type="submit" value="submit" data-target="#modal" class="test input-append btn btn-primary col-xs-2"><span class="glyphicon glyphicon-ok"></span></button>
<div class="form-group col-xs-12">
<input id="checkbox" type="checkbox" name="sub" value="Yes" checked/> Subscribe to newsletter
</div>
</form>
I would greatly appreciate any advice on how to achieve this!
I'm not sure whether I should be trying to use AJAX or some other method, I've yet to learn how to use AJAX so if this would be my best option, a pointer to a decent (preferably comprehensible for beginners) tutorial would be nice :)
UPDATE
Ok, So I am attempting to use an iframe as suggested... But so far have not been able to get the data to submit.
I've not used iframe before, so I'm not sure what I'm doing!
I have added a hidden iframe like so:
<iframe class="hidden" name="iframe_submit"></iframe>
I'm not sure where I should be pointing the form at the iframe.
Previously I had the action of the form pointing at ProcessRequest.cshtml.
I have changed this to formtarget="iframe_submit" is this correct?
I changed the submit button to use a href="~/ProcessRequest....
Now the email is being sent, so the iframe must be loading the ProcessRequest page, however the information from the form is not inserted in the email.
Thanks #mplungjan this worked nicely..
Solution: Hidden iframe
<iframe class="hidden" name="iframe_submit"></iframe>
with
<form class="form-inline" method="post" target="iframe_submit" action="~/ProcessRequest.cshtml">...</form>
and added to the ProcessRequest file:
<script>alert("Thankyou for submitting your email, #customerName.")</script>
Your assistance is very much appreciated, especially since I learnt a new trick!

User Control code behind is not called when published on server

I have a simple user control which is basically a contact form and consists of three text boxes, 1 button and 1 label. I am also using Telerik RadAjaxLoadingPanel and RadAjaxPanel. The markup of the user control is given below,
<telerik:RadAjaxLoadingPanel ID="RALP_ContactForm" runat="server" Transparency="5">
<div class="border" style="display: table; height: 240px; width: 240px; #position: relative;
overflow: hidden; background-color:White">
<div class="border" style="#position: absolute; #top: 50%; display: table-cell; text-align: center;
vertical-align: middle;">
<div class="border" style="width: 100%; #position: relative; #top: -50%">
<img src="images/cf_animation.GIF" alt="Processing Request..." />
</div>
</div>
</div>
</telerik:RadAjaxLoadingPanel>
<telerik:RadAjaxPanel ID="upContactForm" runat="server">
<div id="form-main">
<div id="form-div">
<p class="name">
<asp:TextBox ID="txtContactName" ValidationGroup="ContactForm" CausesValidation="true"
runat="server" name="name" CssClass="validate[required,custom[onlyLetter],length[0,100]] feedback-input"
ClientIDMode="Static" placeholder="Name"></asp:TextBox>
<asp:CustomValidator ID="customValidator" runat="server" ValidationGroup="ContactForm"
ControlToValidate="txtContactName" Display="Dynamic" ClientValidationFunction="ValidateContactName"
ErrorMessage="" ValidateEmptyText="true"></asp:CustomValidator>
</p>
<p class="email">
<asp:TextBox ID="txtContactEmail" ValidationGroup="ContactForm" CausesValidation="true"
runat="server" name="email" CssClass="validate[required,custom[onlyLetter],length[0,100]] feedback-input"
ClientIDMode="Static" placeholder="Email"></asp:TextBox>
<asp:CustomValidator ID="customValidator1" runat="server" ValidationGroup="ContactForm"
ControlToValidate="txtContactEmail" Display="Dynamic" ClientValidationFunction="ValidateContactEmail"
ErrorMessage="" ValidateEmptyText="true"></asp:CustomValidator>
</p>
<p class="text">
<asp:TextBox ID="txtContactComment" ValidationGroup="ContactForm" CausesValidation="true"
TextMode="MultiLine" runat="server" name="text" ClientIDMode="Static" CssClass="validate[required,custom[onlyLetter],length[0,100]] feedback-input"
placeholder="Comment"></asp:TextBox>
<asp:CustomValidator ID="customValidator2" runat="server" ValidationGroup="ContactForm"
ControlToValidate="txtContactComment" Display="Dynamic" ClientValidationFunction="ValidateContactComment"
ErrorMessage="" ValidateEmptyText="true"></asp:CustomValidator>
</p>
<p><asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label></p>
<div class="submit">
<asp:Button ID="btnSubmitContactForm" Width="100%" runat="server" ValidationGroup="ContactForm"
Text="SEND" CssClass="btn-flat gr btn-submit-reg" OnClick="btnSubmitContactForm_Click" />
</div>
</div>
</div>
On the code behind I am just sending the information from the textboxes to an email address. The code for the event when the submit button is clicked is as follow,
protected void btnSubmitContactForm_Click(object sender, EventArgs e)
{
try
{
string AppPath = Request.PhysicalApplicationPath;
StreamReader sr = new StreamReader(AppPath + "EmailTemplates/UserFeedback.htm");
string MailBody = sr.ReadToEnd();
MailBody = MailBody.Replace("<%Name%>", txtContactName.Text.Trim());
MailBody = MailBody.Replace("<%Email%>", txtContactEmail.Text.Trim());
MailBody = MailBody.Replace("<%Comments%>", txtContactComment.Text.Trim());
// Close the StreamReader after reading text from it
sr.Close();
MailMessage message = new MailMessage(
"sender#mymail.com",
"receiver#mymail.com",
"Feedback",
MailBody);
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.myserver.com";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.Credentials = new NetworkCredential("MyUserName", "MyPassword");
try
{
smtp.Send(message);
}
catch
{
}
txtContactComment.Text = "";
txtContactEmail.Text = "";
txtContactName.Text = "";
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Feedback sent successfully!";
}
catch
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Error sending feedback ! ";
}
}
The User control is called like this,
<uc1:FooterContactForm ID="FooterContactForm" runat="server"></uc1:FooterContactForm>
And at the top of the page,
<%# Register Src="ContactForm.ascx" TagName="FooterContactForm" TagPrefix="uc1" %>
Now all this is very simple and works just fine on my test machine. When I publish this in the server then loading image is displayed but code behind is not fired. I have tried to set the dummy text in the label on Page_Load event of the user control but even that test is not displayed on the user control on live server. I am receiving email every time when I submit this locally.
My question is that why the code behind is not called when the user control is published on the live server and is someone else has experienced such issue?
Edit: (Errors found from console)
POST http://test.mywebsite.com/ 500 (Internal Server Error)
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net.XMLHttpExecutor.executeRequest
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net._WebRequestManager.executeRequest
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net.WebRequest.invoke
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._onFormSubmit
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._doPostBackTelerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._doPostBackWithOptions
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
(anonymous function)(index):800
onclick
Second error:
Uncaught Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 Error.create
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._createPageRequestManagerServerError
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._onFormSubmitCompleted
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 (anonymous function)
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 (anonymous function)
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net.WebRequest.completed
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 _onReadyStateChange
When you have something inside an ajax panel, and for some reason starts to not work, then is probably a javascript error that you miss, a file that is not loaded, an exception that you did not see.
In this cases just remove the ajax panel to locate the error on the code, and/or check the javascript console error on the browser.
From your comments sounds that if the user is not authenticated, some javascript files on some folder fail to load because of the security and then you have some javascript errors that not let your code run correctly.

how to get js POST in asp.net webform?

I know its a rudimentary questions, but I am out of practice on webforms. I am using Stripe.js for the first time, and want to use it in conjunction with stripe.net to process the client side. Here is the client code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="StripePage.aspx.cs" Inherits="StripePage.StripePage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
// You need to put your real publish key here.
Stripe.setPublishableKey('pk_test_1nDJ3hA1Mv2Sy9bUoYcBMXmm');
// ...
// I am using jquery to process the payment. It knows what form to
// process it on based on the name 'payment-form'
jQuery(function ($) {
//payment submission
$('#payment-form').submit(function (event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
//if there is a error, it is displayed on the page if there was
//no error this is where it gets sent to the server.
var stripeResponseHandler = function (status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
});
</script>
<form method="POST" id="paymentForm" runat="server">
<span class="payment-errors" runat="server"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<br />
<input id="number" type="text" data-stripe="number" clientidmode="Static" />
<input type="text" size="20" data-stripe="number" runat="server" />
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<br />
<input type="text" size="4" data-stripe="cvc" runat="server" />
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<br />
<input type="text" size="2" data-stripe="exp-month" runat="server" />
</label>
<br />
<input type="text" size="4" data-stripe="exp-year" runat="server" />
</div>
<asp:Button ID="submit" ClientIDMode="Static" runat="server" Text="SubmitPayment" OnClick="submit_Click" />
</form>
</asp:Content>
The last call in JS creates a JSON object that I want to know how to get to on the C# page on the button click:
protected void submit_Click(object sender, EventArgs e)
{
....
}
I am wanting to do the javascript implementation to avoid having to do PCI compliance. Am I approaching this incorrectly? Should it be all Stripe.net to process everything, and skip the js entirely? Or if this is right, how can I get the form post data in the button click event?
Thanks for the tips in the comments. After much perusal of the internet and hair pulling, I walked away for a bit and came back with this solution.
Made the button just a standard html input (not the asp:Button)
Got the posted back information that was being sent via the JavaScript in the Page_Load event like so
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
StripeConfiguration.SetApiKey("[API Secret Key");
NameValueCollection nvc = Request.Form;
string amount = nvc["amount"];
var centsArray = amount.Split('.');
int dollarsInCents = Convert.ToInt32(centsArray[0]) * 100;
int remainingCents = Convert.ToInt32(centsArray[1]);
string tokenId = nvc["stripeToken"];
var tokenService = new StripeTokenService();
StripeToken stripeToken = tokenService.Get(tokenId);
var myCharge = new StripeChargeCreateOptions
{
TokenId = tokenId,
AmountInCents = dollarsInCents + remainingCents,
Currency = "usd"
};
var chargeService = new StripeChargeService();
StripeCharge stripeCharge = chargeService.Create(myCharge);
}
}
Seems like using the NameValueCollection (which lives in System.Collections.Specialized namespace) gave me the ability to grab what I needed from the Request.Form by pulling it out via variable name. Since I new the variable names, it was simply a matter of grabbing them and then following the Stripe .NET library documentation to get the token and process the payment.
I want to just post a comment to the answer, but I'm not allowed to yet. So, this isn't really an answer, more of a response to the OP's own findings.
I'm doing the exact same thing, using Stripe.js. I can simply grab stripeToken using Request.Form, and get all other non-c/c-related fields the usual way in the code-behind (e.g. int Total = PaymentTotal.Value;); but what I'm noting isn't so much about grabbing the data, it's that you have to handle it on Page_Load (or during some later point in the page life cycle), because the Submit button's onclick event is never actually fired, since the form is actually submitted using js and not the button.
So, being all literal and kinda answering the original question, you can't actually get the data in the button click event, w/o firing that event manually on postback (I'm surmising).
Hopefully save someone else some time figuring that out if they come here looking to make Stripe and .NET work together.

Categories

Resources