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.
Related
I am trying to get html textbox value when click on html button without using "runat" attribute.I need to do it in code behind ,is it possible?
<button id="button1" onclick="btnclick">Click Here</button><input type="text" id="txtBox1" name="txtBox12" />
and My code Behind is like:
protected void btnclick(object sender, EventArgs e)
{
string name = Request.Form["txtBox12"];
Response.Write(name);
}
MODIFIED
To access any control in code behind it needs to have runat=server attribute attached to it.
In your case, like you pointed you can transfer the value of input text to asp hidden field and then access
its value on button click in server-side but in this case too you have to place hidden field inside form runat=server tag.
<form id="form1" runat="server">
<input type="text" id="txt" onkeyup="PassValue(this);";/>
<asp:HiddenField ID="hf" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Go" onclick="Button1_Click" />
</form>
-----------------------
<script type="text/javascript">
function PassValue(obj) {
document.getElementById("hf").value = obj.value;
}
</script>
I have following code snippet in my asp.net webpage.
<div id="descDiv" style="display:none;">
<form>
<asp:TextBox ID="inputDesc" Height="200px" Width="100%" runat="server" TextMode="MultiLine" placeholder="Enter any details you know about this city" required="required"></asp:TextBox>
<input type="button" Class="cancel" value="Cancel" OnClick="hideInput('descDiv');" /><asp:Button ID="Submit_Desc" CssClass="submit" runat="server" Text="Submit" OnClick="Submit_Desc_Click" />
</form>
</div>
When I click the submit button I receive this error:
Invalid postback or callback argument. Event validation is enabled using
<pages enableEventValidation="true"/> in configuration or
<%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or
callback events originate from the server control that originally rendered them.
If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to register the
postback or callback data for validation.
This form is enclosed in another main form which has 'runat' attribute. What should I do to correct this problem?
EDIT:
Here is the shortest code to reproduce the problem:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="descDiv">
<form>
<asp:TextBox ID="inputDesc" Height="200px" Width="100%" runat="server" TextMode="MultiLine" placeholder="Enter any details you know about this city" required="required"></asp:TextBox>
<input type="button" class="cancel" value="Cancel" onclick="hideInput('descDiv');" />
<asp:Button ID="Submit_Desc" CssClass="submit" runat="server" Text="Submit" OnClick="Submit_Desc_Click"/>
</form>
</div>
</div>
<form>
<asp:TextBox ID="TextBox1" Height="200px" Width="100%" runat="server" TextMode="MultiLine" placeholder="Enter any details you know about this city" required="required"></asp:TextBox>
<input type="button" class="cancel" value="Cancel" onclick="hideInput('descDiv');" />
<asp:Button ID="Button1" CssClass="submit" runat="server" Text="Submit" OnClick="Submit_Desc_Click"/>
</form>
</form>
</body>
</html>
You cannot have two forms on your page, remove the form tag just under your div. The one to keep has to be the form runat="server" since it's a .net page.
what you can do is use .net buttons and process whatever they do from code behind
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
</form>
protected void Button1_Click(object sender, EventArgs e)
{
// do something with button 1
}
protected void Button2_Click(object sender, EventArgs e)
{
// do something with button 2
}
I am new to web programming. I have a pretty standard page that accepts contact information and I am trying to add validation controls to it. When the user clicks the cancel button nothing is saved so I just want to unload the page and go back to the previous page. My problem is, even the the cancel button has CausesValidation="false the validation events are still firing and a post back does not occur. I am using Visual Studio 2012 and C#. I've created a test page to reduce the code I'm working with to the minimum required code to demonstrate the issue. I have tried the javascript disableValidation() function with both Page_Validation = false; and the loop to disable the individual validation controls without success. When I check Page_Validation it is false, and the loop throws the exception Page_Validators is undefined.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestMe.aspx.cs" Inherits="ElmoWeb.TestMe" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Simple Little Test Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="uxEmail" runat="server" placeHolder="email address" type="email" AutoCompleteType="Email"></asp:TextBox>
<asp:RegularExpressionValidator ID="uxEmailValidator" runat="server"
ControlToValidate="uxEmail"
ValidationExpression="^[a-zA-Z][\w\._%+-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
ErrorMessage="The email address is invalid"
EnableClientScript="false" ValidationGroup="testing"
Display="Static"/>
</div>
<div>
<asp:Button ID="Submit" runat="server" Text="Submit" CausesValidation="true" UseSubmitBehavior="true" ValidationGroup="testing" />
<asp:Button ID="Cancel" runat="server" Text="Cancel" CausesValidation="false" UseSubmitBehavior="true" ValidationGroup="FakeValidationGroup" />
</div>
<div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List" HeaderText="You must correct the following errors." ValidationGroup="testing" />
</div>
</form>
</body>
</html>
Currently the code behind just writes a message to the output window so I can see if the post back occurred.
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("TextMe.aspx Page_Load event, sender = " + sender.ToString() + ", EventArgs = " + e.ToString());
}
The natural way of solving issues where two or more submit buttons should behave in a different way is to use validation groups.
A validation group is set with the ValidationGroup attribute on both a submit button and a group of validators. The same value binds a button and validators and only validators with the same value of the attribute fire when the button is clicked.
In your case, setting the ValidationGroup on the accept button and your validators to "Accept" and leaving the default (empty) value on the cancel button would solve your issue. This is much simpler than any of the workarounds you tried.
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" %>
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.