Click event not recognizing textbox in asp.net - asp.net

My click event is showing the error "the name login_password and login_username does not exist in the current context" when I am trying to access my text box from their ids. please help me identify the error as I am just a beginner.
click event:
protected void LogIn_Clicked(object sender, EventArgs e)
{
string usern = "abc";
string pass = "123";
if (login_username.Text == usern && login_password.Text == pass)
{
Response.Redirect("Default.aspx");
}
else
{
label1.Text = "LogIn";
}
}
}
login form:
<form id="login" runat="server">
<h1 style = "Background-color: deepskyblue;">
Log in to your account!</h1>
<p class="register">
<a style = "color: deepskyblue;" href="Login.aspx?logoff=true">Logoff</a>
</p>
<div>
<label for="login_username">
Username</label>
<input type="text" name="username" id="login_username" class="field required" title="Please provide your username" onclick="return login_username_onclick()" />
</div>
<div>
<label for="login_password">
Password</label>
<input type="password" name="password" id="login_password" class="field required"
title="Password is required" />
</div>
<div class="submit">
<asp:Button ID="Button1" Text="Log in" runat="server" OnClick="LogIn_Clicked"
BackColor="#00B2EE" ForeColor="White" />

Those aren't Asp.net Controls. Add the runat="server" attribute:
<input type="text" name="username" id="login_username" class="field required" title="Please provide your username" onclick="return login_username_onclick()" runat="server"/>
Or you can add Asp.net controls:
<asp:TextBox runat="server" ID="login_username" CssClass="field required" ToolTip="Please provide your username"></asp:TextBox>

your inputs for username and password are html only - they need a runat="server" tag to get them in the code behind. The usual way is to use an asp:Textbox though.

Related

Aspx content page, unable to execute send email code

I'm using an asp content page that uses site master file. I'm particularly confused about the runat=server with the labels and getting the vb.net to execute. I tried this but its not working:
<div class="card-body">
<asp:Label ID="Label1" runat="server" />
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name" required>
</div>
<div class="form-group" runat="server">
<asp:Label for="email" runat="server" Text="Email address"></asp:Label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" required>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" rows="6" required></textarea>
</div>
<div class="mx-auto">
<asp:Button type="submit" class="btn btn-primary text-right" ID="Btn_SendMessage" runat="server" Text="Submit"></asp:Button>
</div>
I tried putting the html code in a form but errors saying cannot have nested form, so confused as to how to send the html to the vb.net code
VB.NET code:
Protected Sub Btn_SendMessage_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim Email As String = FindControl("email").ToString
Dim Name As String = FindControl("name").ToString
Dim Message As String = FindControl("message").ToString
Dim Mail As New MailMessage
Dim SMTP As New SmtpClient("smtp.gmail.com")
Mail.Subject = Name
Mail.From = New MailAddress(Email)
SMTP.Credentials = New System.Net.NetworkCredential("xxxx#gmail.com", "xxxxxxxx") '<-- Password Here
Mail.To.Add("xxxxxxx#gmail.com")
Mail.Body = Message
SMTP.EnableSsl = True
SMTP.Port = "587"
Try
SMTP.Send(Mail)
Label1.Text = "Message sent"
Catch ex As Exception
Label1.Text = ex.ToString
End Try
End Sub
The page refreshes and nothing happens, I don't even think the VB.NET executes.
Here's a working sample based on your code:
ASPX
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div class="card-body">
<asp:Label ID="Label1" runat="server" />
<div class="form-group">
<label for="name">Name</label>
<asp:Label ID="Label4" runat="server" AssociatedControlID="TextBoxName" Text="Name"></asp:Label>
<asp:TextBox ID="TextBoxName" runat="server" CssClass="form-control" placeholder="Enter name"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ErrorMessage="*" ControlToValidate="TextBoxName"></asp:RequiredFieldValidator>
</div>
<div class="form-group" runat="server">
<asp:Label ID="Label3" runat="server" AssociatedControlID="TextBoxEmail" Text="Email address"></asp:Label>
<asp:TextBox ID="TextBoxEmail" runat="server" CssClass="form-control" placeholder="Enter name"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" runat="server" ErrorMessage="*" ControlToValidate="TextBoxEmail"></asp:RequiredFieldValidator>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<asp:Label ID="Label2" runat="server" AssociatedControlID="TextBoxMessage" Text="Message"></asp:Label>
<asp:TextBox ID="TextBoxMessage" runat="server" TextMode="MultiLine" CssClass="form-control" Rows="6"></asp:TextBox>
</div>
<div class="mx-auto">
<asp:Button type="submit" class="btn btn-primary text-right" ID="Btn_SendMessage" runat="server" Text="Submit" OnClick="Btn_SendMessage_Click"></asp:Button>
</div>
</div>
</form>
</body>
</html>
Code behind
Protected Sub Btn_SendMessage_Click(sender As Object, e As EventArgs) Handles Btn_SendMessage.Click
Dim Mail As New MailMessage
Dim SMTP As New SmtpClient("smtp.gmail.com")
Mail.Subject = TextBoxName.Text
Mail.From = New MailAddress(TextBoxEmail.Text)
SMTP.Credentials = New System.Net.NetworkCredential("xxxx#gmail.com", "xxxxxxxx") '<-- Password Here
Mail.To.Add("xxxxxxx#gmail.com")
Mail.Body = TextBoxMessage.Text
SMTP.EnableSsl = True
SMTP.Port = "587"
Try
SMTP.Send(Mail)
Label1.Text = "Message sent"
Catch ex As Exception
Label1.Text = ex.ToString
End Try
End Sub
Tags with the runat="server" attribute are ASP.NET server side controls which render as their HTML counterparts in the resulting web page sent to the browser. During the server side processing of the page you can access them in your code directly using their IDs.
Please note that I've used server side validation controls for the required fields. You may need to add the following setting in the Web.config file in case you receive a runtime error about Unobtrusive Validation:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
Hope it helps. I am using Visual Studio 2017 and the target framework is .NET 4.6.1.

How to send text to content page as query string from Master Page

I have a search textbox that I tried wrapping in a form element:
<form id="searchForm" method="GET" action="Search.aspx">
<input name="term" type="text" id="searchTerm" class="nav-search" size="30" />
<input type="submit" value="submit" style="display:none;"/>
</form>
I can't get it to redirect to the content page (Search.aspx) with the query string (term) from the Master Page.
I tried wrapping it in an ASP:Panel and using the DefaultButton Property but that wouldn't call the Click event in code behind.
I'm perplexed as I've searched for a solution for hours and this seems like a such common task. Thanks.
Change your code to this
<input name="term" type="text" id="searchTerm" runat="server" class="nav-search" size="30" />
<asp:Button ID="searchsubmit" OnClick="searchsubmit_Click" runat="server" Text="Search" />
in Site.Master.cs add something like this
protected void searchsubmit_Click(object sender, EventArgs e)
{
Response.Redirect("~/search.apsx?content=" + searchTerm.text);
}
This will allow to search with button click, if you want to hide it, add also panel around first code, saying that this is a button to automatically press when enter is pressed Something like this:
<asp:Panel ID="UserPanel" runat="server" DefaultButton="searchsubmit">

How to create Button_Click() Event for Bootstrap Button?

Bootstrap login form is below:
<form class="form-vertical login-form" runat="server" action="~/Default.aspx">
<label class="control-label visible-ie8 visible-ie9">User Name</label>
<input class="m-wrap placeholder-no-fix" type="text" placeholder="UserName" name="username"/>
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="m-wrap placeholder-no-fix" type="password" placeholder="Password" name="password"/>
<button type="submit" class="btn green pull-right" aria-pressed="undefined">
Log In <i class="m-icon-swapright m-icon-white"></i>
</button>
</form>
When the button is clicked, I want to create the connection to the database. So, I need to have sth like this:
protected void (ButtonName)_Click(object sender, EventArgs e)
{
string connStr = "Initial Catalog=LoginCheck; Data Source=MYCOMPUTER; User id=sa; password=000000;";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
...
}
But it doesn't work like ASP.NET. If I double-click on the button when I am designing, it's not taking me to code behind. Please put me in the right direction!
In ASP.Net, you want to use Server control if you want to post back.
Most of the time, <form> tag is located inside Master Page, so you cannot style it easily.
Here is an example -
<form id="form1" runat="server">
<div class="form-vertical login-form">
<asp:Label runat="server" ID="UsernameLabel"
AssociatedControlID="UserNameTextBox"
CssClass="control-label visible-ie8 visible-ie9">User Name
</asp:Label>
<asp:TextBox runat="server" ID="UserNameTextBox"
CssClass="m-wrap placeholder-no-fix" />
<asp:Label runat="server" ID="PasswordLabel"
AssociatedControlID="PasswordTextBox"
CssClass="control-label visible-ie8 visible-ie9">Password
</asp:Label>
<asp:TextBox runat="server" ID="PasswordTextBox"
CssClass="m-wrap placeholder-no-fix" />
<asp:LinkButton runat="server" ID="SubmitLinkButton"
CssClass="btn btn-default pull-right"
OnClick="SubmitLinkButton_Click">
Log In <i class="m-icon-swapright m-icon-white"></i>
</asp:LinkButton>
</div>
</form>
But it doesn't work like ASP.NET
Your code (aka "code-behind") looks like it expects ASP.Net server controls e.g. <asp:Button runat="server" id="foo"... so it can do a Postback which is the the ASP.NET "web forms" way.
Having said that, you can try
assigning a bootstrap css class to an ASP.net server control to make it look like a bootstrap button (styling)
keep your existing HTML above handle the normal HTTP POST and not deal with server controls (and deal with request.form)
It's your choice based on what works for you. Either way the core concept is based on standard HTTP POST (html form post, asp.net web forms "postback").
Hth...

asp.net request.form

public ActionResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Customerid"]);
objCustomer.CustomerCode = Request.Form["code"];
objCustomer.Amount = Convert.ToDouble(Request.Form["amount"]);
return View(objCustomer);
}
This is my action in controller(MVC 2 aspx):
<form action="DisplayCustomer" method="post">
Customer id:-
<input type="text" id="Customerid" /><br />
Customer Code:-
<input type="text" id="code" /><br />
Customer amount:-
<input type="text" id="amount" /><br />
<input type="submit" value="click here" />
</form>
This is the view. When someone hit the submit button it is directed to a new page:
<div>
<b> ID</b> <%= Model.Id %><br />
<b> Code </b><%=Model.CustomerCode %><br />
<b> Amount</b> <%=Model.Amount %><br />
</div>
I always get 0 in Id and Amount while blank in CustomerCode.
Any clue? Why this is happening? What is wrong?
Your issue here is that you set the id, and not the name. Set the name to get the post back value. Eg:
<input type="text" name="Customerid" />
read also: HTML input - name vs. id in the line "Used on form elements to submit information"

Conditionally disable validation

I have form with few text boxes which goes through validation (both server and client sides). In the form I have buttons: "Next", "Back", "CanceL". So I don't need validation to fireup then user clicks "back" or "cancel" buttons. How can I achieve this?
Thanks in advance!
Some sample:
<div class="buttons">
<input type="submit" name="cancelButton" value="" />
<input type="submit" name="backButton" value="" />
<input type="submit" name="nextButton" value="" />
</div>
<% using (Html.BeginForm()) { %>
<p>
<table style="width: 200px">
<tr><td align="center" colspan=2><%= Html.ValidationMessageFor(m => m.street) %><%= Html.DropDownListFor(m => m.street, Model.streetsList) %></td></tr>
<tr><td colspan=2> </td></tr>
<tr><td valign="bottom" align="right" style="width: 75px"><%= Html.LabelFor(m => m.flatNumber) %>:</td><td align=left><%= Html.TextBoxFor(m => m.flatNumber, new { maxlength = 6, style = "width: 48px;" })%> <%= Html.ValidationMessageFor(m => m.flatNumber) %></td></tr>
</table>
<br />
<input type="submit" class="refusal button red floatL" name="cancelButton" value="" />
<input type="submit" class="back button green floatL" name="backButton" value="" />
<input type="submit" class="continue button green floatR marR" name="nextButton" value="" />
</div>
<div class="clear">
</div>
<% } %>
At the server side I use DataAnnotations attributes for validation.
the Button class has a CausesValidation property - if that is set to false, validation won't be triggered on postback.
Example:
<asp:Button id="btnCancel" CausesValidation="false" onClick="bntCancel_Click" Text="Cancel" runat="server" />
Note that this will disable the ASP.NET validators - if you have your own validation you will need to disable it another way.
Surround the text boxes with a form and turn next, back, and cancel into submit buttons. On event onsubmit, assign a method which returns true if the form is valid and should proceed to send it to the server, otherwise false.
So I would expect something along the lines of:
<form id="navigatorForm">
<!-- Various text forms here -->
<input type="submit" value="Back" onsubmit="back()" />
<input type="submit" value="Next" onsubmit="next()" />
<input type="submit" value="Cancel" onsubmit="cancel()" />
<input type="hidden" id="operation" name="operation" value="" />
</form>
<script type="text/javascript">
function validate() {
// Perform validation here
// If okay, return true, else false
}
function next() {
document.getElementById('operation').value = 'next';
if(!validate()) {
alert('Form is not filed correctly. Please pay more attention!');
return false; // Do not send to server!
} else {
return true;
}
}
function back() {
document.getElementById('operation').value = 'back';
return true;
}
function cancel() {
document.getElementById('operation').value = 'cancel';
return true;
}
</script>
Notice that unlike next(), back() and cancel() unconditionally return true, meaning that the request is sent to the server in any circumstance. At this point, on the server side, you'd need only to check to see if operation is next to know whether or not you should perform further testing.

Resources