C# ASPX - Form Submission Query - c#

I have a C# aspx form in which I need to input it's data into an SQL database and then return a response saying successful or not. I have no idea how to get the form data that is sent from the Default.aspx page. My basic code structure is below:
Default.aspx
<form runat="server" name="aForm" action="Results.aspx" method="post" onsubmit="ValidateForm()">
<input name="firstname" type="text" />
<input name="surname" type="text" />
<input type="submit" value="Submit" />
</form>
Results.aspx.cs
public partial class AwardsForm : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack){
Response.Redirect("Default.aspx");
} else (this.IsPostBack) {
writeResults(FormSubmit());
}
protected boolean FormSubmit() {
// get form data and insert it into SQL
// return true/false based on success
}
protected void writeResults(boolean results) {
if (results == true) {
Response.Write ("Success");
} else {
Response.Write ("Failed");
}
}
}

You can get the posted form data through Request.Form["key"], or, if your form elements are decorated with runat="server" then you should be able to grab them by id right in your code behind
<asp:TextBox id="yourTb" runat="server"></asp:TextBox>
string postedText = yourTb.Text;
Or you can do (though this is much less common)
<input type="text" runat="server" id="yourOtherTb" />
string otherPostedText = yourOtherTb.Value;
Or if you're working with purely html form inputs:
<input type="text" id="clientTb" name="clientTb" />
string clientText = Request.Form["clientTb"];

You can try by the following code.
string firstname = Request.Form["firstname"]
string surname = Request.Form["surname"]

Since you are doing something like this
<input name="firstname" type="text" />
<input name="surname" type="text" />
<input type="submit" value="Submit" />
the name attribute of the input controls are posted back to the server(IIS). Hence you would do this.
If(IsPostBack)
{
string firstName = Request.Form["firstname"];
string surName = Request.Form["surname"];
if(string.IsNullOrEmpty(firstName))
{
Response.Write("Firstname is required this form");
}
}

Related

Aspx form doesn't pass data to code behind file

I'm try to send the data in email field to the code and then work with it. However, the data never reaches the code, I've tried even setting breakpoints and it never halts at the breakpoint.
Form-
<form class="cd-form" runat="server" >
<label class="cd-label" for="email" runat="server">Console</label>
<input type="text" class="cd-email" name="email" id="email" runat="server" placeholder="Enter address to test connection">
<input type="submit" class="cd-submit" value="submit" runat="server" id="submit" onserverclick="Accept" />
<div class="cd-loading"></div>
</form>
Code behind file-
protected void Accept(object sender,EventArgs e)
{
String a = email.Value;
if( email.Value == "a#a.com" )
{
Response.Redirect("README.aspx");
}
}
Change
Email.value
To email.text
Change in your line
String a = email .Value ;
To
String a email.text;
protected void Accept(object sender,EventArgs e)
{
String a = email.text;
if( email.text== "a#a.com" )
{
Response.Redirect("README.aspx");
}
}

how to create button click event for form method?

I have Form tag in my layout page. I cant use form tags in content page, so I am using Form method="post" how to create button click event for this and how to give validation for html input type?
<form class="contact-form-title white" method="post">
<label id="lblFirstName" runat="server" title="First Name:">First Name:</label>
<input type="text" id="txtFirstNam" runat="server" /><br />
<label id="lblLastName" runat="server" title="Last Name:">Last Name:</label>
<input type="text" id="txtLastNam" runat="server" /><br />
<label id="lblEmail" runat="server" title="Email ID:">Email ID:</label>
<input type="text" id="txtEmail" runat="server" />
<label id="lblMessage" runat="server" title="Message">Message:</label>
<textarea id="txtMessag" runat="server" ></textarea><br />
<input type="submit" class="btn delicious f-center" runat="server" id="btnContac" name="SUBMIT" onserverclick="btnContac_Click" style="height:25%; width:10%;"/>
</form>
Back-End :
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnContac_Click(object sender, EventArgs e)
{
string FirstName = txtFirstNam.Value;
string LastName = txtLastNam.Value;
string EmailID = txtEmail.Value;
string Message = txtLastNam.Value;
}
Approach 1 : client side control
In Code behind use ispostback to catch the post back event,
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// write form population code;
}
else
{
//you will get posted data here;
}
}
to validate on client side, write your own java script validator something on below line.
<script type="text/javascript">
function validate()
{
var Firstname = document.getElementById('txtFirstNam').value
if (Firstname == "")
{
alert("Enter First Name");
return false;
}
if (LastName == "") {
alert("Enter Last Name");
return false;
}
}
</script>
then call this validator on submit button click
<input type="submit" class="btn delicious f-center" runat="server" id="btnContac" name="SUBMIT" onclick="return validate();" style="height:25%; width:10%;"/>
Option 2 : Server side control
Change all input and button into server controls (add runat=server) controls into server , then you can catch the event on server side in code behind like you are trying to do. good place to start
In server side approach, you have chance to use built in validators.
ASP.NET provides the following validation controls:
RequiredFieldValidator.
RangeValidator.
CompareValidator.
RegularExpressionValidator.
CustomValidator.
ValidationSummary.
for validator refer here

How to pass HTML parameters to ASP.NET?

I am making a web service project using Bootstrap (HTML&CSS) , Microsoft Access and ASP.NET.
I found a code from W3SCHOOLS of bootstrap login form :
<body>
<form method="POST" action="Login.aspx">
<div class="container">
<h2>Login area</h2>
<form class="form-inline" role="form">
<div class="form-group">
<label for="email">UserName:</label>
<input type="text" class="form-control" id="username1" name="username" placeholder="Enter UserName"/>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password1" name="password" placeholder="Enter password"/>
</div>
<button type="submit" onclick="SubmitForm" class="btn btn-default">Submit</button>
</form>
</div>
And this is the C# code :
protected void SubmitForm(object sender, EventArgs e)
{
if (Page.IsValid)
{
string name=string.Format("{0}",Request.Form["username"]);
string pass = string.Format("{0}", Request.Form["password"]);
int userId;
userId = LoginService.GetUserId(name, pass, 0, 1);
if (userId == 0)
{
MessageBoxShow(Page, "UserName does not exists.");
}
else
{
MessageBoxShow(Page, "You are successfully connected.");
Session["userId"] = userId.ToString();
SalService.DeleteFromSal();
}
}
}
When I am running the page and entering username and password , the page doesnt show the message and I cant connect with the user name.
Put a breakpoint and check what is happening at the code-behind and what values are you receiving.
Also, Try using onserverclick instead of onclick.
<input id ="txt" runat="server" type="text">
and in behine
txt.value=#Your
Your HTML is not formatted using ASP serverside controls, however you can still get it to work. You have to change your button to a submit button.
<input type="submit" value="OK"/>
and then change your code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string name=string.Format("{0}",Request.Form["username"]);
string pass = string.Format("{0}", Request.Form["password"]);
int userId;
userId = LoginService.GetUserId(name, pass, 0, 1);
if (userId == 0)
{
MessageBoxShow(Page, "UserName does not exists.");
}
else
{
MessageBoxShow(Page, "You are successfully connected.");
Session["userId"] = userId.ToString();
SalService.DeleteFromSal();
}
}
}
Make sure that the code behind is for a page called login.aspx and should be called login.aspx.cs
There should be a login.aspx page and should have a valid page directive pointing to the code behind.
You will also need a function for MessageBoxShow and the Webservice should be referenced.

How to populate html input from server side

I am not quite sure how to attack this, basically I have two html fields in my aspx page:
<input type="text" name="fname" />
<input type="text" name="lname"/>
Now i would like to populate them from the server side when the page loads based on some data collected from the database, basically this data is stored in two properties
public string FirstName { get; set;}
public string LastName {get; set;}
How can I pass the value from such properties into the html inputs On_Load ?
I would appreciate the help.
Here is one way, assuming Webforms:
<input type="text" name="fname" value="<%:FirstName%>" />
<input type="text" name="lname" value="<%:LastName%>" />
If using .NET before 4.0, replace the <%: with <%=.
Another option is to change the input types to be runat="server" and assigning the values directly on the server side.
Alternatively add runat="server" to your elements, then you could do something like
fname.Value = FirstName;
lname.Value = LastName;
The info I was looking for was like this:
protected void Page_Load(object sender, EventArgs e)
{
address.Value = Request.QueryString["lat"];
address1.Value = Request.QueryString["long"];
}
takes values from the URL string and puts them in an HTML input="text"
http://localhost:64375/Map.aspx?lat=detroit&long=windsor
Enter Address A: <input runat="server" name="address" id="address" type="text" />
Enter Address B: <input runat="server" name="address1" id="address1" type="text" />
thanks Ash and Oded for the combined answer

Get posted value In C# ASP.NET

I have a dynamic form that allow to add many fields dynamically,
I Know how to get the value of single field in aspnet using : Request.Form["myField"],but here i have more than field and i dont know the count of these fields since these are dynamic
the fields name is "orders[]"
ex:
<form>
<input type="text" name="orders[]" value="order1" />
<input type="text" name="orders[]" value="order2" />
<input type="text" name="orders[]" value="order3" />
</form>
In php,
i get the values as an array by accessing $_POST['orders'];
ex:
$orders = $_POST['orders'];
foreach($orders as $order){
//execute ...
}
how can I do this in c# ?
Use Request.Form.GetValues.
Request.Form is a NameValueCollection, an object that can store a collection of items under the same key and the ToString displays the values in CSV format.
Markup:
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<asp:Button Text="text" runat="server" OnClick="ClickEv" />
Code behind:
protected void ClickEv(object sender, EventArgs e)
{
var postedValues = Request.Form.GetValues("postField[]");
foreach (var value in postedValues)
{
}
}
You would use Request.Form[]. Or if your form and fields had runat="server" and ids, you could just use the id in the codebehind and the .Text() method to access its value.
You can access everything that gets sent back to the server by using the Request object.
Request.Form.Items
Is a collection that will contain the item you are looking for.

Categories