ASP.NET and the classic HTML form - c#

I am implementing a standard payment system, which sends some information to 3rd part form. I've a checkout object which stores all my shopping information: ID, products bought, price - you name it.
People are transfered to an ASPX page which has an implementation as seen below.
Currently I have the following problem:
The values send on the inputs which has the runat="server" is 0. Therefore I get an error. However, in the OnPreInit event in the code behind, i set the values of amount, accepturl and orderid. I can see the hidden fields get the correct information when the page is loaded - but when the form is fired (which apparently happens before the OnPreInit event), it is still 0.
How do I solve this problem? Basically I need to use an HTML form which opens a popup window (which HAS to show on page load), where I have to set the hidden fields. Should be quite simple, but after I've used hours on this I would really appreciate some help.
Currently my implementation is like this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="BetalingMedKort.aspx.cs" Inherits="BetalingMedKort" %>
<!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">
<script type="text/javascript" src="http://www.epay.dk/js/standardwindow.js"></script>
<title></title>
</head>
<body onload="open_ePay_window()">
<form action="SomeUrl" runat="server" method="post" name="ePay" target="ePay_window" id="ePay">
<input type="hidden" name="merchantnumber" value="MyStaticMerchantNumber" />
<input type="hidden" name="language" value="1" />
<input type="hidden" name="currency" value="208" />
<input type="hidden" name="amount" id="amountField" runat="server" />
<input type="hidden" name="accepturl" id="acceptUrlField" runat="server" />
<input type="hidden" name="orderid" id="orderIdField" runat="server" />
<input type="hidden" name="declineurl" value="SomeUrl" />
</form>
<div>
If the ePay Payment Window does not open automatically please click on the button below to open it.
<br /><br />
Notice! If you are using a pop-up blocker, you must hold down the CTRL key as you click the button.
<br /><br />
<input type="button" value="Open the ePay Payment Window" onClick="open_ePay_window()">
</div>
</body>
</html>
Thanks so much...

Try setting the input values in the page's Init or Load events. ViewState isn't available during PreInit (though there may be some exceptions).
If you absolutely have to perform your logic during PreInit then this page may have a workaround for you.

Related

Codebehind does not create button click event

I have created a ASP.NET Empty Website in a new install of Visual Studio 2017 Community. I am attempting to replicate the steps shown by the following tutorial: https://youtu.be/5dCAXwhjIYU
I'm simply planting three text boxes on the form, along with a submit button. When i double click the button, The IDE simply highlights the HTML for the button in the source view of the page. It does not create the event handler in the code-behind as shown in the video and as expected.
I manually created the event handler for the button click in the code behind. When I try to run the code, it is telling me that the fields I'm referencing do not exist:
Error CS0103 The name 'UserName' does not exist in the current context
Here's my HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Users.aspx.cs" Inherits="Users" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
UserName<br />
<input id="UserName" type="text" /><br />
UserEmail<br />
<input id="UserEmail" type="text" /><br />
UserCampus<br />
<input id="UserCampus" type="text" /><br />
<input id="SaveUser" type="submit" value="submit" /></div>
</form>
</body>
</html>
The C# code:
public partial class Users : System.Web.UI.Page
{
protected void SaveUser_Click(object sender, EventArgs e)
{
SqlConnection BIGateConnection = new SqlConnection("Data Source=xxxxxxx;Initial Catalog=xxxxxxx;Integrated Security=True");
{
SqlCommand BIGateSQLCmd = new SqlCommand("Insert into [BIGateway].[dbo].[User] (UserName, userEmail, userCampus) VALUES (#userName, #userEmail, #userCampus)", BIGateConnection);
BIGateSQLCmd.Parameters.AddWithValue("#", UserName.Text);
BIGateSQLCmd.Parameters.AddWithValue("#", UserEmail.Text);
BIGateSQLCmd.Parameters.AddWithValue("#", UserCampus.Text);
}
}
}
What the heck am I doing wrong?
if you have taken HTML text box then code is as follows:
<input id="UserName" type="text" /><br />
In this you will have to add the line on your own as runat="server"
It will look as follows:
<input id="UserName" type="text" runat="server"/><br />
Then you can use it for serverside.
Hope its helpful.
Video doesn't show the ASPX page. I believe he used TextBox and Button server controls.
<form id="form1" runat="server">
<div>
UserName<br />
<asp:TextBox runat="server" ID="UserName"/><br />
UserEmail<br />
<asp:TextBox runat="server" ID="UserEmail"/><br />
UserCampus<br />
<asp:TextBox runat="server" ID="UserCampus"/><br />
<asp:Button runat="server" ID="SaveUser" OnClick="SaveUser_Click" Text="Submit"/>
</div>
</form>
If he used regular html input with runat="server", he will have to access the value as UserName.Value inside Button1_Click event which he did not.
Afais you didn't find the click event to the button.
Add
SaveUser.OnClick += SaveUser_Click;
To the page_load event.
In general I would prefer asp:Button instead of input.
In fact it's rendered as a input control. But with more options. But indeed runat="server" is missing for the input.

prevent Asp.NET button from submitting form

So, I have a Paypal form that worked wonders. However, I now need to add a coupon field, where someone can enter a code, and get a reduction based on whatever the backend replies.
This all works wonderfully, but I've ran into an issue when adding the option to know before checking out whether your code is valid or not. Currently, my form (once simplified) looks like this :
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"
id="payPalForm" runat="server">
<asp:TextBox runat="server" ID="txtCode" />
<asp:Button Text="Validate" OnClick="ValidateDiscount" runat="server" />
<asp:Label ID="txtDesc" runat="server" />
<input type="submit" name="Submit" value="Pay up!" />
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="upload" value="1" />
...
</form>
With the backend having the function :
protected void ValidateDiscount(object sender, EventArgs e)
{
this.txtDesc.Text = "fetch from database using: " + txtCode.Text;
}
My issue is that wheneve I click on the Validate button, the form is submitted and I end up on the Paypal website. I used Jquery at first with preventDefault(), but that actually prevents my server-side function from firing. I've also tried putting a standard <button> or <input type='button'> tag instead, but I couldn't get it to fire my server-side function.
Is there any way to have the Validate button not submit the form, or should I just remove the action from the form and manually submit the form when clicking on the submit button?
You have set your form action to post to PayPal.
This is the action:
action="https://www.sandbox.paypal.com/cgi-bin/webscr"
Here is where you have it in you form tag:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"
id="payPalForm" runat="server">
Remove this from your form tag and it should postback to your application.

onsubmit function wont fire while having a runat=server attribute

<%# Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" MasterPageFile="MasterPage.master" %>
<asp:Content ID="ContentPlaceHolder1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>
<asp:Content ID="ContentPlaceHolder2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<br />
<div id="signupform">
<form class="signupform" name="formreg" runat="server" onsubmit="return valform()"> <br/>
<input dir="rtl" type="text" name="uname" class="uname"/> </br>
<input dir="rtl" type="text" name="fname" class="fname"/> </br>
<input dir="rtl" type="text" name="lname" class="lname"/> </br>
<input dir="rtl" type="password" name="pword" class="pword"/> </br>
<input dir="rtl" type="password" name="rpword" class="rpword"/> </br>
<input dir="rtl" type="text" name="mmail" class="mail"/> </br>
<input dir="rtl" type="text" name="rmail" class="rmail"/> </br>
<input dir="rtl" type="text" name="gil" class="gil"/> </br>
<input type="checkbox" name="anon" value="True" class="dropan"/></br>
<input type="submit" name="sub" class="subbutton" value=""/>
<%=registrationstatus %>
</form>
</div>
</asp:Content>
This is my code, My problem is that the onsubmit="return valform()" attribute on my form wont fire if the runat="server" attribute exists, they can't work together please help me I am clueless why these two attributes wont work together
This is because you can't use both together. As said in the docs -
<input type="text" id="Textbox1" runat="server">
Doing this will give you programmatic access to the HTML element on the server before the Web page is created and sent down to the client. The HTML element must contain an id attribute. This attribute serves as an identity for the element and enables you to program to elements by their specific IDs. In addition to this attribute, the HTML element must contain runat="server". This tells the processing server that the tag is processed on the server and is not to be considered a traditional HTML element.
Here is the reference.
http://msdn.microsoft.com/en-us/library/aa478973.aspx
under section - Using HTML Server Controls
So, HTML with run='server' will not be treated as a normal Html element and thus will always be processed by the server. If you want to override the default behavior, you have to bind your javascripts with after the html is loaded in the browser, may be using jQuery or something similar. With jQuery something like this would help -
$(function(){
$("#formreg").submit(function(){
return valform();
});
});
By examing your code, I reach on conclusion that you might be using another form tag on Master page and there is no javascript issue. Only one form tag(Server Side) can exists either on a master page or content page. They can not be nested. When you would use runat="Server" attribute on both of form tags then error occurs saying "A page can have only one server-side Form tag". So remove runat="server" attribute from one of the form tags, onsubmit would begin firing.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});

Post data to another site from code behind

I have a web form which is posting a few fields to a payment site. The structure the example is using is
<form method="post" action="<%= FormAction %>">
<input type="hidden" name="Hash" value="<%= sHash %>" />
<input type="hidden" name="MID" value="<%= sMID %>" />
......
<div class="submit">
<input type="submit" value="Post Data" />
</div>
Within the example project they have set the same variables within the code behind file (after declaring them) with values. When the button above is clicked it posts the data to the relevant page without errors and the user is redirected to the payment page.
So i am now trying the same under the click event of an image button on my site but doesnt work:
<asp:ImageButton ID="ButtonCheckout" runat="server" Text="Go to payment page" ImageUrl="~/Images/Payment.gif" />
and of course it doesnt work, ive added all the markup as above and added all sample code.
When i run the app it flashes and stops. I look in Fiddler and notice its not going to the payment site at all. The masterpage has declared in it - incase this makes any difference.
Reading around it seems i could use the image button to post the data and do exactly the same as the submit button (submit button is above which was part of the sample application from the payment provider) by using the onClick event in the markup with Javascript but im struggling to understand how to tie it all together and lost to what i could do next to get this working?
You can't just post form data with an image button. You need to submit the form data - otherwise your image button is just a link. I do this a lot with Javascript.
Try adding this.form.submit() to the clientclick. Or name your form and use this.formname.submit()
Either of those should post your form data.
You can such so write:
<form id="Form2" method="post" runat="server" action="<%= FormAction %>">
<input type="hidden" name="Hash" value="<%= sHash %>" />
<input type="hidden" name="MID" value="<%= sMID %>" />
......
<div class="submit">
<asp:ImageButton ID="ButtonCheckout" runat="server" Text="Go to payment page"/>
</div>
</form>
but you must add a few attributes in top of web page,eg:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" EnableEventValidation="false" EnableViewStateMac="false" ValidateRequest="false" ViewStateEncryptionMode="Never" %>

Form fields not retained on postback

I'm developing a website using EPiServer. I have a form which submits to itself.
On submit, I check if there are any fields missing. If yes, then error message is shown.
The problem is that my fields are reset when submitted.
I could check this using jQuery, but I'm not. I'm cheking this from code behind.
I've tried setting EnableViewState=true sevceral places, but no luck.
Here's part of my code:
<asp:Content ID="Content3" ContentPlaceHolderID="RightContentPlaceHolder" runat="server">
<asp:Panel ID="panelComplaint" runat="server">
<li>
<h3>Postnummer*</h3>
<input id="senderPostCode" name="postCode" type="text" size="20" enableviewstate="true" />
<asp:Label runat="server" id="lblPostCode" CssClass="missingField" Text="Mangler tekst" Visible="false" />
</li>
<li>
<h3>Post sted*</h3>
<input id="senderCity" name="city" type="text" size="100" />
<asp:Label runat="server" id="lblCity" CssClass="missingField" Text="Mangler tekst" Visible="false" />
</li>
<li>
<div class="spacer10px"></div>
<button type="submit" name="Send" >Send me</button>
</li>
</asp:Panel>
</asp:Content>
What do I need to do, in order to retain form fields?
Have you tried adding runat="server" to the input fields? As far as I'm aware, this is needed to ensure that asp.net round-trips data properly. I'm not sure if there's anything specific to EPiServer that would make that differ.
The enableviewstate attribute, unless it's specific to EPiServer, won't actually be doing anything.
If having the ID mashed up by ASP.net is a problem, consider upgrading to .NET 4.0, if you can, as this provides ways for you to control how the ID's are modified. If not, you could try placing a friendly translation into the page that you can then access via JQuery, for example:
<script language="javascript" type="text/javascript">
function getSenderPostCode() { return eval('<%=senderPostCode.ClientID%>'); }
var senderPostCodeField = JQuery('#getsenderPostCode');
alert(senderPostCodeField.length());
</script>
That said, having "getSenderPostCode()" to reference would mean that you could probably skip the step with JQuery of getting a reference to it, so the following would work:
alert(getSenderPostCode().length();
By adding runat="server" to your controls you then wouldn't need to use Request.Form["senderPostCode"].ToString() to access the content of that field, you could instead access it directly:
var contentOfSenderPostCode = senderPostCode.Value.ToString();

Categories

Resources