How to pass HTML parameters to ASP.NET? - c#

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.

Related

Button Click doesn't work to make a H1 visible (asp.net)

I'm new at ASP.NET and web programming in general, here's my issue.
I have this DIV in my .aspx:
<div class="login">
<input type="text" placeholder="Usuário" name="usuario" id="usuario" runat="server"><br>
<input type="password" placeholder="Senha" name="senha" id="senha" runat="server"><br>
<button type="submit" class="btn-sucess" id="btn" runat="server" onserverclick="btn_Click" onclick="btn_Click">Login</button>
<h1 id="lbl1" runat="server" visible="false">Sucess</h1>
</div>
If the user clicks on the submit button it should be visible as it's written here in my aspx.cs
protected void btn_Click(object sender, EventArgs e)
{
lbl1.Visible = true;
}
Nothing happens. Why it doesn't work?
You're setting it to Visible false when rendering the control. Remove the visible property from aspx code and handle it in Page_Load event. All controls need to be inside form.
aspx
<form runat="server">
<div class="login">
<input type="text" placeholder="Usuário" name="usuario" id="usuario" runat="server"><br>
<input type="password" placeholder="Senha" name="senha" id="senha" runat="server"><br>
<button type="submit" class="btn-sucess" id="btn" runat="server" onserverclick="btn_Click" onclick="btn_Click">Login</button>
<h1 id="lbl1" runat="server">Sucess</h1>
</div>
</form>
Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Visible = false;
}
With button click
protected void btn_Click(object sender, EventArgs e)
{
lbl1.Visible = true;
}
Also, if you want to handle anything at a client side, then alone use a javascript function btn_Click. But make sure that returns true and so the form will be submitted to the server.
Something like this,
Javascript
<script type="text/javascript">
function btn_Click()
{
return true;
}
</script>

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

'Global' variables Razor

I'm creating a form so members of a site can change the passwords for their accounts, and I'd like to display a message explaining mistakes the users made while filling the fields (such as password too short, needs at least a non-alphanumeric character, etc.). I'd like to display these messages in the same page, beside the field names. Here's my code:
#helper RenderForm()
{
<form method="post">
<p>Change your password below</p>
<div><label for="currentPassword">Current Password</label>
<input type="password" id="currentPassword" name="currentPassword"/></div>
<div><label for="newPassword">New Password:</label>
<input type="password" id="newPassword" name="newPassword"/></div>
<div><label for="confirmPassword">Confirm New Password</label>
<input type="password" id="confirmPassword" name="confirmPassword"/></div>
<div><input type="submit" id="submit" name="submit" value="submit"/></div>
</form>
}
#helper Message(string message)
{
<p>#message</p>
}
<style type="text/css">
p,label {color:black;}
</style>
#{
if(!IsPost) {
#RenderForm();
}
else {
var account = Membership.GetUser();
var currentPassword = HttpContext.Current.Request["currentPassword"];
if(Membership.ValidateUser(account.UserName, currentPassword)){
var newPassword = HttpContext.Current.Request["newPassword"];
var confirmPassword = HttpContext.Current.Request["currentPassword"];
if(check(newPassword, confirmPassword)){
account.ChangePassword(account.ResetPassword(), newPassword);
}
}
else {
#Message("The password provided didn't match with the database.");
}
}
}
#functions{
List<string> check(string newPassword, string confirmPassword)
{
//just a place holder
return false;
}
}
I've tried adding a List to be filled when an error was found, and when the form was reloaded the message would be displayed, but the RenderForm() function can't find any reference to the List. How can I display these messages?
You should use the built in validation that comes with the Web Pages framework. I have an article that explains how to use it: http://www.mikesdotnetting.com/Article/191/Validation-In-Razor-Web-Pages-2

C# ASPX - Form Submission Query

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");
}
}

Categories