Stuck with classic ASP form submission - asp-classic

I am new to classic asp. I have developed a simple asp form where I am doing a form submission to access database. I got a code to do a form validation on fields but the code works only when I you same asp code. When I change the form method to different asp file, validation doesn't work.
Form.asp
....code
<%
Dim send, txtengineer, txtcaseid, txtassetno, txtusername, txtgroup, txtLOB, txtmodel, txtsim, countError
send = Request.Form("submit")
txtengineer = Request.Form("engineer")
txtcaseid = Request.Form("caseid")
txtasset = Request.Form("asset")
txtusername = Request.Form("username")
txtgroup = Request.Form("group")
txtLOB = Request.Form("lob")
txtmodel = Request.Form("model")
txtsim = Request.Form("sim")
countError = 0
%>
<form method="post" action="form.asp">
....
<%
if send <> "" AND txtcaseid = "" then
Response.Write "<span class=""message""> << Enter Case no.</span>"
countError = countError + 1
end If
%>
DB.asp
This is the code where I want to submit the collected field value. Which is working fine. I have forced to keep wherein I am want to do
I want to validate first then submit the form afterwards. I know I am doing something stupid.
Need some guidance to fix the code blocks.
Thanks.

The problem with having the form submit to a different page is, what do you do if there are errors? Tell the user to hit their "back" button? For that reason alone, I'd recommend putting the DB code in the same page as the form. If you can't do that, you need to move your server-side validation to the DB page. The client-side validation would still be on the form page. (Note that if you're only going to do one type of validation, it must be server-side.)
If you do everything in one page, the basic structure would look like this:
<html><head>[etc.]
<%
Const errstr = "<span class='err'>*</span>"
Dim txtengineer, txtcaseid '[etc.]
Dim counterror(8) '- 8 = number of fields
counterror(0) = 0
If Request.Form <> "" Then
txtengineer = Request.Form("engineer")
'etc. with other fields
Validate
If counterror(0) = 0 Then
SavetoDB
Response.Redirect "Success.asp"
End If
End If
Sub Validate()
If txtengineer = "" Then
counterror(1) = 1
counterror(0) = counterror(0) + 1
Else
'do whatever other cleanup/validation you need
End If
'etc. for other fields
End Sub
Sub SavetoDB()
'code to write stuff to database goes here
End Sub
%>
<script>
function validate(){
//client-side validation goes here
}
</script>
</head>
<body>
<%
If counterror(0) > 0 Then
Response.Write "<p>Please fill out the required fields (*) below.</p>"
End If
%>
<form method="post" action="form.asp">
<p>Engineer: <input type="text" name="engineer" value="<%=txtengineer%>" size="30" maxlength="50">
<%If counterror(1) = 1 Then Response.Write errstr%>
</p>
[etc. with other fields]
<p><input type="submit" name="Btn" value="Submit" onclick="validate();"></p>
</form>
</body>
</html>

Related

Cannot pass value to page through HtmlGenericControl Property

Here is the .aspx file
<form id="form1" runat="server">
<input type="text" id="StringValue" runat="server"/>
<datalist id="dataList" runat="server"></datalist>
<% CreateContent(_sql)%>
</form>
And here is the .vb file (CreateContent)
Protected Sub CreateContent(ByVal sql As String)
Dim optList As New List(Of String)
optList = GetData(sql)
Dim table As New DataTable()
table.Columns.Add(New DataColumn("DataOptions"))
For Each opt In optList
table.Rows.Add(opt)
Next
For Each row In table.Rows
dataList.InnerHtml = dataList.InnerHtml & vbCrLf & String.Format("<option value='{0}'>", row(0))
Next
MsgBox(dataList.InnerHtml)
End Sub
When I tested the page, the MsgBox could actually show all the <option> elements. However, these contents can only exist in server side. <datalist> is always empty in page source. Anyone can explain what prevent the content being passed to the page and how to solve it?

asp.net and vb.net code for sending emails to multiple email address via smtp

I am a new in coding asp.net and vb.net. I have a web form built with asp.net and vb.net .
In the front end of the there are four fields constructed as below.
Recipient Mailing List : Drop down List (the options in the drop down list are such as Managers, HR, Admin, IT etc. Each option name contains multiple email addresses. i.e selecting one option means The user selects one group of of email address in the recipient field )
From Field : Text box (Read Only )
Subject : Text box
Message : Textarea
Send email button
The asp.net front end code is like below.
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<div class="aux-body">
<div class="aux-body-content">
<div class="form-element">
<label>Recipient Mailing list </label>
<select runat="server" class="" id="comMailingList" datatextfield="name" datavaluefield="id"></select>
</div>
<div class="form-element">
<label> From </label>
<input style="width: 98%;" runat="server" id="txtFrom" type="text" value="Careers portal" readonly="readonly" />
</div>
<div class="form-element">
<label> Subject </label>
<input style="width: 98%;" runat="server" id="txtSubject" class="msubject" type="text" />
</div>
<div class="form-element">
<label> Message </label>
<textarea style="width: 98%; height: 100px;" runat="server" id="txtText" ></textarea>
</div>
<div id="button-group">
<asp:LinkButton runat="server" ID="btnSend" CssClass="btn" Text="Send Email"></asp:LinkButton>
</div>
</div>
</div>
</asp:Content>
In the back end i have structured the VB.net code like following. But i am unable to write the code that will send the email.
Partial Class E4_Candidate_broadcast
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
If Not IsNothing(Request("b")) Then
cid.Value = Request("b")
End If
litMyEmail.Text = UserEmail
comMailingList.DataSource = Lists
comMailingList.DataBind()
End If
End Sub
Public ReadOnly Property Lists() As DataTable
Get
Return DB.GetData("select ml.id, ml.name + ' (' + cast( count(mlc.mailinglistid) as nvarchar(10)) + ' contacts)' name from mailinglist ml join mailinglistcontact mlc on ml.id = mlc.mailinglistid where ml.deleted = 0 and ml.createdby in (select userid from employeruser where employerid = #eid) group by ml.id, ml.name having count(mlc.mailinglistid) > 0 order by ml.name", DB.SIP("eid", LocalHelper.UserEmployerID()))
End Get
End Property
Protected Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If Not String.IsNullOrWhiteSpace(txtSubject.Value) Then
''Selects the recipients name and email address
Dim contacts = DB.GetData("select title, name, surname, email from mailinglistcontact where mailinglistid = #mlid", DB.SIP("mlid", comMailingList.Value)), _
mailers = New DataTable(), _
mailerqueue = New DataTable(), _
scheduleat = Now
For Each contact As DataRow In contacts.Rows
''''Code for sending email''''
Next
Response.Redirect("broadcast-sent-complete.aspx?i=" & cbId)
End If
End Sub
End Class
I have seen several examples by googling and found several links. But I am surely not understanding many things which are essential to code for sending emails.
I will be very much obliged if you help me write the code to send emails.
Thank you
Update
I have tried the following code. but its not working. i.e. the email is not sending.the code is going to the exception and saying message sending mailed. please have a look at my code and point me my error.
Dim message As New MailMessage()
For Each contact As DataRow In contacts.Rows
Try
Dim Client As New System.Net.Mail.SmtpClient
With Client
If WebConfigurationManager.AppSettings("smtpserver").Length > 0 Then
.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory 'Net.Mail.SmtpDeliveryMethod.Network
.PickupDirectoryLocation = "c:/outbox/"
.Host = WebConfigurationManager.AppSettings("smtpserver")
Else
.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis
End If
With message
Dim FromAddress As MailAddress = New MailAddress("noreply#mypeoplebiz.com")
.From = FromAddress
.[To].Add(contact.Item("email").ToString())
.Subject = txtSubject.Value
.IsBodyHtml = True
.Priority = MailPriority.Normal
.BodyEncoding = Encoding.Default
If Not String.IsNullOrWhiteSpace(txtHtml.Value) Then
.Body = txtHtml.Value
End If
If Not String.IsNullOrWhiteSpace(txtText.Value) Then
.Body = txtText.Value
End If
End With
.Send(message)
End With
Catch Ex As Exception
_error = Ex.Message
End Try
Next

save the checked items in checkbox to session

Need help. I want to save the items that are check in my checkbox to a Session.
What I'm doing is get the value of the items that are checked and store it in an array. Then I will assign that value as Session Name and assign a value of 1 to the session.
This is the code that I'm using but it only gets the first item that is checked.
dim checkboxList
checkboxList = request.Form("schedule")
checkboxList = split(checkboxList, ",")
for each i in checkboxList
Session(i) = 1
next
for example If I check A and B on my Checkbox I should get
Session("A")=1 and Session("B")=1
but the only thing i'm getting is Session("A")=1
I tried checking if I'm getting the right item on the my Array by Using this code and the data is correct.
dim checkboxList
checkboxList = request.Form("schedule")
checkboxList = split(checkboxList, ",")
for each i in checkboxList
response.write(i)
next
Here is my Html Code.
<form class="well" method="post" action="applicationSave.asp">
<div class="controls">
<input type="checkbox" id="onShifts" name="schedule" value="onShifts" <% if Session("onShifts") = 1 then response.Write("checked") end if %> /> On Shifts?<br>
<input type="checkbox" id="nightShifts" name="schedule" value="nightShifts" <% if Session("nightShifts") = 1 then response.Write("checked") end if %> /> Night Shifts?<br>
<input type="checkbox" id="partTime" name="schedule" value="partTime" <% if Session("partTime") = 1 then response.Write("checked") end if %> /> Part Time?<br>
<input type="checkbox" id="fullTime" name="schedule" value="fullTime" <% if Session("fullTime") = 1 then response.Write("checked") end if %> /> Full Time<br>
<input type="checkbox" id="holidays" name="schedule" value="holidays" <% if Session("holidays") = 1 then response.Write("checked") end if %> /> Holidays/Sundays?<br>
<input type="checkbox" id="projectBasis" name="schedule" value="projectBasis" <% if Session("projectBasis") = 1 then response.Write("checked") end if %> /> Project Basis
</div>
</form>
This is because values delimited with ", " (comma-space), instead "," only.
So, before working with array make "trimming" items:
Dim i
For i = 0 To UBound(checkboxList)
checkboxList(i) = Trim(checlboxList(i))
Next
Another way - write Session(Trim(i)) = 1 in for statement.
BTW: Commonly, your code is unsafe. E.g, you have some session bool variable Session("IsAuthorized"). Visitor can send request to your .asp file with value schedule=IsAuthorized...

error with form action

I have the following C# code:
AddCommentForm = string.Format("<form name=\"AddComment\" method=\"post\" runat=\"server\" id=\"add_comment_form\"><p> TITLE: <input type =\"text\" name=\"Title\" /></p><p> Contnt <textarea name=\"Content\" ></textarea></p><p> <button type=\"submit\">Submit!</button></p></form>");
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID;
The problem is that there is an error in the second line:
System.NullReferenceException was caught
My question is how can I this error?
And why with this code it works?
<%
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID.ToString();
%>
<form name="AddComment" method="post" runat="server">
AddCommentForm = string.Format("<form name=\"AddComment\" method=\"post\" ....
Above code is not valid. AddCommentForm is a HtmlForm control - not a string. Besides, you cannot create another form tag inside a form in ASP.Net.
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID.ToString();
Basically, you are Cross-Site Scripting. Although it compiles, it won't work. When you get to ViewArticle.aspx page, you'll get an error.
If you want a form inside ASP.Net, use iframe.

How to pass value from asp to aspx

I am in asituation ,where i have to redirect from asp to aspx page with parameter.I tried a lot of option,but the redirection is working ,but i couldnt the value in my aspx.cs page.
Below is my asp
Dim objASPError,strRemoteIP
Set objASPError = Server.GetLastError
The below is not working with parameter
'Response.Status = "301 Moved Permanently"
'Response.AddHeader "Location", "/404.aspx? err="+objASPError
'Response.End
I even tried by setting the hiddenn value and accessed the form element in aspx.cs
document.getElementById("hdnErr").value=objASPError
The below is also not working with objASPError
response.Redirect("/404.aspx?err="&objASPError)
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="404.aspx">
<input type="hidden" id="hdnErr" />
</form>
</body>
</html>
My aspx.cs
Label lbl = new Label();
Exception ex = Server.GetLastError();
string message=string.Empty;
if(Request.Form["hdnErr"] != null)
{
message = Request.Form["hdnErr"].ToString();
}
if (Request.QueryString["err"] != null)
{
String temp = Request.QueryString["err"].ToString();
lbl.Text = temp;
}
Thanks
Question
I understand sending the values through querystring is not a best option ... How to send error object from asp to aspx..
try changing
<input type="hidden" id="hdnErr" />
to
<input type="hidden" name="hdnErr" />
Also, Server.GetLastError returns an object so you can't combine it with a string. Take a look at the example in the msdn doc.
ASPError Object

Resources