Cannot pass value to page through HtmlGenericControl Property - asp.net

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?

Related

Stuck with classic ASP form submission

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>

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

Getting Value From Input text from input type button

so i have been trying to reach the value from a input text and set it in on a string, i've tried 4 different ways and for some reason I get String = "" or String Is Nothing
Code VB Behind
Public Sub subscriber(sender As Object, e As EventArgs)
Dim check_Mail As String = subs_text.Value()
If check_Mail = Nothing Then
alertJava("Working Empty")
Else
alertJava(check_Mail.ToString())
End If
End Sub
tried as well
Dim checkmail as string = Page.Request.Form("subs_text")
Dim checkmail as string = Request("subs_text")
Dim checkmail as string = Request(subs_text.value())
HTML Code I Have
<div class="input-group"> ------
<input id="subs_text" runat="server" name="subs_text" type="text" class="form-control">
<placeholder="Email Adress"> / -----
<span class="input-group-btn"> ----
<input type="button" runat="server" onserverclick="subscriber" class="btn btn-primary" value="JoinUS"> ----
</span>
</div>
You are not setting the value="" attribute. Therefore, its always empty
Is actually the value since the form is not in a Runat=server the postback value comes back in the uniqueID instead of the actual value so
Dim Check_Main as String = Request.Form(TEXTFIELD_ID.UniqueID)
hope this helps someone

How do I resolve "Object reference not set to an instance of an object" error?

I am passing the following via the request object in codeBehind:
Get the Requested code to be created.
Dim Code As String = Request("code").ToString()
and below is my markup page called barcodes.aspx:
<form id="Form1" method="post" runat="server">
<img src="barcodes.aspx?code=XXXXX" alt="barcode" />
<asp:Image id="myBarCode" runat="server"></asp:Image>
</form>
Why am I getting the error above?
If Request("code") is null, calling .ToString() on it will give you a null reference exception.
Check if Request("code") is null or not. If it is null, then you will get an object reference error when calling ToString()
I think this has to deal with the fact that you are trying to get the query string value of an image on the page. Request() will only get the querystring for the 'requested page', which is the page you are on, not the image itself. Therefore your code will always be null if you are expecting it to pull from the image source
You need to actually submit the form (POST) or pass the parameters in the URL (GET) to get the request parameters via the Request object. Two easy ways (of many) to do this:
Option 1. Keep just your barcodes.aspx and barcodes.aspx.vb. In barcodes.aspx put:
<form id="Form1" method="post" runat="server">
<input type="hidden" name="code" value="XXXXX" />
<asp:Image id="myBarCode" runat="server"></asp:Image>
<asp:Button runat="server" Text="Submit"></asp:Button>
</form>
In barcodes.aspx.vb put in the Page_Load:
If PostBack Then
Dim code As String = Request.Form("code")
If Not String.IsNullOrEmpty(code) Then
' Generate your image here, a code has been specified
End If
End If
Then just hit the submit button on your aspx page.
Option 2. Split it into two aspx pages but basically same as above.
In submitme.aspx put this (for a POST, click the button):
<form id="Form1" method="post" runat="server">
<input type="hidden" name="code" value="XXXXX" />
<asp:Button runat="server" Text="Submit" PostBackURL="barcodes.aspx"></asp:Button>
</form>
Or this (for a GET, click the link):
Click Me
In barcodes.aspx.vb put this in Page_Load (works for either the GET or POST option):
Dim code As String = Request("code")
If Not String.IsNullOrEmpty(code) Then
' Generate your image here, a code has been specified
End If
In barcodes.aspx you would then simply need:
<asp:Image id="myBarCode" runat="server"></asp:Image>
You can simply remove ToString(), as Request(item key) returns String:
Dim Code As String = Request("code")
Check to see that the query string value exists:
Dim Code as String = String.Empty
If Not Request.QueryString("code") Is Nothing Then
Code = Request.QueryString("code")
End If
You could also use the string.isnullorempty() function to test the contents of the request.querystring value

FindControl method cannot locate the control on the page

Ive tried searching for hours now and cannot find out why my code (aka, me.) is failing
Basically... I have a listview control which I'm passing a datatable of products (ID, Name, Description and Price columns), and im trying to make it so that when the "checkout" button is pressed, it parses through all the controls on the page, finds all the controls with the correct ID's and adds the items values to the cart.
ive checked all my ID's in the source code and they match up to the ones being requested by the FindControl method.
the error getting thrown back is:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Line 21: For I = 1 To counter
Line 22: Dim cartItem As New Core.Types.CartItem
Line 23: cartItem.Name = CType(productsContainer.FindControl("product" + I.ToString()), HtmlGenericControl).InnerText
Line 24: cartItem.Quantity = Convert.ToInt32(CType(productsContainer.FindControl("quantity" + I.ToString()), HtmlSelect).Value)
Line 25: cartItem.Price = Convert.ToDecimal(CType(productsContainer.FindControl("price" + I.ToString()), HtmlGenericControl).InnerText.Remove(0, 1))
my .aspx code:
<div class="productsContainer" id="productsContainer" runat="server">
<asp:ListView runat="server" ID="lsvProducts">
<LayoutTemplate>
<ul class="lsvProducts">
<li class="highlight">
<div class="productName">
Product
</div>
<div class="productQuantity">
Number of Licenses
</div>
<div class="productPrice">
Price
</div>
</li>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div style="display: none;">
<%=setCurrent()%>
</div>
<input type="hidden" id='productID<%#Eval("ID")%>' />
<div class="productName" id='product<%=currentItem%>'>
<%#Eval("Name")%>
</div>
<div class="productQuantity">
<select id='quantity<%=currentItem%>'>
<option selected="selected"
value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class="productPrice" id='price<%=currentItem%>'>
<%#"$" + Convert.ToDouble(Eval("Price")).ToString()%>
</div>
</li>
</ItemTemplate>
</asp:ListView>
</div>
<div class="clearer">
</div>
<div class="purchaseButton">
<asp:Button ID="btnAddCart" runat="server" Text="Add to Cart" />
</div>
</div>
and my code behind:
Dim counter As Int32
Public currentItem As Int32
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'get all active products to display in the listing
Dim query As String = "SELECT * FROM Products WHERE Active = 1"
Dim dt As DataTable = DAL.Data.GetDataTable(query, "MainDB")
counter = dt.Rows.Count
lsvProducts.DataSource = dt
lsvProducts.DataBind()
End Sub
Protected Sub btnAddCart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddCart.Click
'create a new instance of the cart
Dim cart As New Core.Types.Cart
'foreach item in the listing, find its details and add it to the shopping cart
For I = 1 To counter
Dim cartItem As New Core.Types.CartItem
cartItem.Name = CType(productsContainer.FindControl("product" + I.ToString()), HtmlGenericControl).InnerText
cartItem.Quantity = Convert.ToInt32(CType(productsContainer.FindControl("quantity" + I.ToString()), HtmlSelect).Value)
cartItem.Price = Convert.ToDecimal(CType(productsContainer.FindControl("price" + I.ToString()), HtmlGenericControl).InnerText.Remove(0, 1))
cartItem.ID = Convert.ToInt32(CType(productsContainer.FindControl("productID" + I.ToString()), HtmlGenericControl).InnerText)
cart.AddItem(cartItem)
Next
If (cart.isEmpty) Then
'empty cart, go nowhere. show a message saying the carts empty and to choose something.
Else
Response.Redirect("~/Checkout.aspx")
End If
End Sub
Public Function setCurrent()
currentItem = currentItem + 1
Return currentItem
End Function
Please help... this is driving me insane!
Thanks in advance :)
If you're in a datagrid/ repeater/ listview, to use the "FindControl" method, you'll have to iterate through the data items in the list view, then for each item peform the find control method. e.g. in C#:
foreach(RepeaterItem item in Repeater1.Items)
{
Literal lit = (Literal)item.FindControl("controlId");
}
I'm not sure thats the exact syntax but you get what I mean. You can't just use the find control method on the listview Id - the Ids of server controls in each item get re-written because you're looping through a collection...
Cheers, Sean
FindControl only looks in the current naming container. If you wish to find controls from a different naming container, you should have your own (recursive) implementation. For example:
private Control FindControlRecursive(Control parent, string id)
{
Control controlFound = parent.FindControl(id);
int i = 0;
while (controlFound == null && i < parent.Controls.Count)
{
controlFound = FindControlRecursive(parent.Controls[i++], id);
}
return controlFound;
}
After that use FindControlRecursive(productsContainer, "product" + I.ToString())
It looks like your nested controls are just basic Html controls? I'm not sure they'll be registered with ASP.NET unless you have runat="server" to register them as server-side controls.
It's been a while since I've done heavy ASP.NET dev, but in my prior experience we always used server-side controls and had no problems.
The other thing I noticed was that if your ContentPlaceHolder for a child page is nested inside a LoggedInTemplate inside a LoginView on a masterpage, then you can forget about using FindControl to grab the handle on a control inside the child page.

Resources