Aspx content page, unable to execute send email code - asp.net

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.

Related

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...

Click event not recognizing textbox in 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.

Using AJAX to make multiple pages be called on one page. Create Person Method stopped working

I have been searching on here on the web everywhere for two DAYS to find this. As of yet I have not found what I need. I am not sure if it is because I am doing something weird with AJAX or what but here is my problem if you can help please do.
I am trying to make a website that only has multiple pages but uses AJAX and JQuery to give the illusion of having one page. The URL does not change like it is supposed to but when I try to create a salesperson or login using the AJAX loaded page it does not work. It looks like it does but it does not actually submit the data input as the code behind is never hit on the separate pages. The following code is my AJAX page.
/// <reference path="jquery-1.8.2-vsdoc.js" />
$(document).ready(function () {
$('#ViewAllUsers').click(function () {
$.ajax({
type: 'POST',
url: "/ViewAllUsers(test).aspx",
success: function (result) {
var main = $('#Main');
main.html($('#Main', result).html());
}
});
});
$('#Button1').click(function () {
$.ajax({
type: 'POST',
url: "/Login.aspx",
success: function (result) {
var main = $('#Main');
main.html($('#Main', result).html());
}
});
});
$('#AddItem').click(function () {
$.ajax({
type: 'POST',
url: "/admin/AddItem.aspx",
success: function (result) {
var main = $('#Main');
main.html($('#Main', result).html());
}
});
});
$('#CreateSalesAccount').click(function () {
$.ajax({
type: 'POST',
url: "/admin/CreateSalesAccount.aspx",
success: function (result) {
var main = $('#Main');
main.html($('#Main', result).html());
}
});
});
$('#ViewAllOrderHistory').click(function () {
$.ajax({
type: 'POST',
url: "/admin/ViewOrderHistory.aspx",
success: function (result) {
var main = $('#Main');
main.html($('#Main', result).html());
}
});
});
});
This code is the admin page which is the page that uses the AJAX buttons to go to the other pages while staying on the admin page.
<%# Page Title="" Language="vb" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="AdminPage.aspx.vb" Inherits="PyriteGoldPresentation.AdminPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="../Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="../Scripts/PyriteGoldAjax.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id = "Main">
<input type="button" id="ViewAllUsers" value="View All Users" />
<input type="button" id="AddItem" value = "Add Item" />
<input type="button" id="CreateSalesAccount" value="Create A Sales Account" />
<input type="button" id="ViewAllOrderHistory" value="View Order History" />
</div>
</asp:Content>
And Finnaly here is the create salesman page and the code behind it.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="CreateSalesAccount.aspx.vb" Inherits="PyriteGoldPresentation.CreateSalesAccount"%>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="../Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="../Scripts/PyriteGoldAjax.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="Main">
<div style="width: 400px; margin-left:auto; margin-right:auto;">
<div class="row">
<h2>
Create Sales Account
</h2>
</div>
<div class="row">
<span class="column1">
<asp:Label ID="FirstNameLabel" runat="server" Text="First Name"/>
</span>
<span class="column2">
<asp:TextBox ID="FirstNameTextField" runat="server" Width="137px"/>
</span>
<span class="column3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*Required Field"
ControlToValidate="FirstNameTextField"/>
</span>
</div>
<div class="row">
<span class="column1">
<asp:Label ID="LastNameLabel" runat="server" Text="Last Name"/>
</span>
<span class="column2">
<asp:TextBox ID="LastNameTextBox" runat="server" Width="137px"/>
</span>
<span class="column3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*Required Field" ControlToValidate="LastNameTextBox"/>
</span>
</div>
<div class="row">
<span class="column1">
<asp:Label ID="EmailLabel" runat="server" Text="E-Mail Address"/>
</span>
<span class="column2">
<asp:TextBox ID="EmailTextBox" runat="server" Width="134px"/>
</span>
<span class="column3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*Required Field" ControlToValidate="EmailTextBox"/>
</span>
</div>
<div class="row">
<span class="column1">
<asp:Label ID="VerifyEmailLabel" runat="server" Text="Verify E-Mail"/>
</span>
<span class="column2">
<asp:TextBox ID="VerifyEmailTextBox" runat="server" Width="136px"/>
</span>
<span class="column3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*Required Field" ControlToValidate="VerifyEmailTextBox"/>
</span>
</div>
<div class="row">
<span class="column1">
<asp:Label ID="PasswordLabel" runat="server" Text="Password"/>
</span>
<span class="column2">
<asp:TextBox ID="PasswordTextBox" runat="server" Width="138px"
TextMode="Password"/>
</span>
<span class="column3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="*Required Field" ControlToValidate="PasswordTextBox"/>
</span>
</div>
<div class="row">
<span class="column1">
<asp:Label ID="VerifyPasswordLabel" runat="server" Text="Verify Password"/>
</span>
<span class="column2">
<asp:TextBox ID="VerifyPasswordTextBox" runat="server" Width="138px"
TextMode="Password"/>
</span>
<span class="column3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="*Required Field" ControlToValidate="VerifyPasswordTextBox"/>
</span>
</div>
<div class="row" style="color:Red;">
<asp:CompareValidator ID="EmailValidator" runat="server" ErrorMessage="**E-mail Feilds Must Match" ControlToCompare="EmailTextBox" ControlToValidate="VerifyEmailTextBox"/><br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="**E-mail Addresses must follow the pattern user#domain.com" ControlToValidate="EmailTextBox"
ValidationExpression="\w+([-+.']\w+[-]*)*#\w+([-.]*\w+)*\.\w+([-.]\w+)*"/><br />
<asp:CompareValidator ID="PasswordValidator" runat="server" ErrorMessage="**Password Fields Must Match" ControlToCompare="PasswordTextBox" ControlToValidate="VerifyPasswordTextBox"/>
</div>
<div>
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</div>
</div>
</div>
</asp:Content>
Code Behind
Imports PyriteGoldBLL
Imports PyriteGoldModel
Public Class CreateSalesAccount
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("permissionValue") <> 3 Then
Response.Redirect("~/Home.aspx")
End If
End Sub
Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
Dim userLogic As New UserLogic()
Dim user As New User()
With user
.FirstName = FirstNameTextField.Text
.LastName = LastNameTextBox.Text
.Email = EmailTextBox.Text
.Password = PasswordTextBox.Text
.Activated = True
.Permission = 2
End With
userLogic.CreateUser(user)
End Sub
End Class
I'm not 100% following what you're trying to achieve.. though making a stab at this anyway :)
You're trying to call an actual page in your AJAX, rather than trying to call a webmethod - which is what you need to do.. you can't call what you're trying to call in the way you're trying to call it...
I would suggest you create a web service which has all the methods you need, such as login, addItem etc. These methods will need to take in the properties you need, I.E Login may need a username and password.
If you rather not create a web service then you will have to put all these methods into the same page that the ajax is on.
So for example: for your ajax login
The URL is to your web service, followed by '/' followed by the method name.
$('#Button1').click(function () {
$.ajax({
type: 'POST',
url: "/MyWebservice.asmx/Login",
data: "{'username':'" + YourUserNameVar + "', 'password':'" + YourPasswordVar +"'}",
success: function (result) {
var main = $('#Main');
main.html($('#Main', result).html());
}
});
});
The method to receive this call would look something like:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function Login(ByVal username As String, ByVal password as string) As Object
'' Do your login here and return whatever it is you need to return
'' i have used 'Object' for this function by way of example
End Function
This answer could of course be fleshed out with far more info, though this is more intended to get you started and on the right path.
UPDATE:
You need to learn a little about consuming web methods/web services with AJAX. Have a look at this simple tutorial. shows all the steps you need to get started :)

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"

Assign TextBox Value to the session in MVC

In MY MVC Application I used input Type Textbox
and i need to assign that value to the Session how?
Im using code like
<input type="text" id="textbox1" name="namebox" />
<input type="text" id="textbox2" name="agebox" />
<% HttpContext.Current.Session["Name"] =textbox1; %>
<% HttpContext.Current.Session["Age"] = textbox2; %>
But i got error pls help on this....
Why would you prefer Session instead of hidden input box? Well, I think you should use name rather than id of your textbox.
Try this and let me know if there is problem.
<input type="text" id="textbox1" name="namebox" />
<input type="text" id="textbox2" name="agebox" />
<% HttpContext.Current.Session["Name"] = namebox; %>
<% HttpContext.Current.Session["Age"] = agebox; %>
have you tryed this:
<input type="text" id="textbox1" name="namebox" />
<input type="text" id="textbox2" name="agebox" />
<% HttpContext.Current.Session["Name"] = textbox1.value; %>
<% HttpContext.Current.Session["Age"] = textbox2.value; %>
Edit: try
<% HttpContext.Current.Session["Name"] =Request.Form["textbox1"]; %>
Try this:
<input type="text" value="#Session["Name"].ToString()"/>

Resources