ASP.net writing code behind variable to HTML page code - asp.net

Hey all i am trying to get this:
<div id="subpg_main">
<%= theHeadering %>
</div>
<!-- END BODY PAGE ------------------------->
To work within my HTML code.
The code behind just has this:
Public Class thankyou
Inherits System.Web.UI.Page
Public theHeadering As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim theName As String = "Bob Barker"
Dim theEmail As String = "bobb#thepriceisright.com"
If theForm = "contact" Then
theHeadering = "<H1>Thank you " & theName & " for contacting us!</H1><BR />"
theHeadering += "We will be contacting you via your email address at " & theEmail & " within 24 hours."
End If
End Sub
End Class
However, when i run the page i get the following error:
Compiler Error Message: BC30451: 'theHeadering' is not declared. It may be inaccessible due to its protection level.

Add a function and call it from the HTML
<div id="subpg_main">
<%= TheHeadering()%>
</div>
<!-- END BODY PAGE ------------------------->
Public Class thankyou
Inherits System.Web.UI.Page
Private headering As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim theName As String = "Bob Barker"
Dim theEmail As String = "bobb#thepriceisright.com"
If theForm = "contact" Then
headering = "<H1>Thank you " & theName & " for contacting us!</H1><BR />"
headering += "We will be contacting you via your email address at " & theEmail & " within 24 hours."
End If
End Sub
Public Function TheHeadering() As String
Return headering
End Function
End Class

Try with this
EDIT
HTML CODE
<div id="subpg_main">
<%# TheHeadering()%>
</div>
<!-- END BODY PAGE ------------------------->
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim theName As String = "Bob Barker"
Dim theEmail As String = "bobb#thepriceisright.com"
If theForm = "contact" Then
theHeadering = "<H1>Thank you " & theName & " for contacting us!</H1><BR />"
theHeadering += "We will be contacting you via your email address at " & theEmail & " within 24 hours."
End If
'Bind your expression with the markup code
Me.DataBind()
End Sub

open the designer page page.aspx.designer.vb
and add:
Protected theHeadering As String
you will now have everything working.
This is done automatically, but sometimes, the automatic part can fail.
Here is an example creating an empty WebForms project. Full image here.

It should be
Public Property theHeadering As String = ""
And not:
Public theHeadering As String = ""

My best guess is that the Page Directive of the Mark up code is pointing to another class which the have the same property
theHeadering As String = ""
but its not a Public access level.

Related

System.Net.Mail - Sending two emails?

Using the following function:
Public Sub SendMail(ByVal SendFrom As String, ByVal SendTo As String, ByVal Subject As String, ByVal Body As String)
Dim client As New SmtpClient
Dim message As New MailMessage
message.Body = Body
message.Subject = Subject
message.From = New MailAddress(SendFrom)
message.To.Add(New MailAddress(SendTo))
client.Port = "25"
client.Host = "smtp.myserver.com"
client.Send(message)
End Sub
I call it with
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
Dim iandamsb As New StringBuilder
iandamsb.AppendLine("Please make the following changes:")
iandamsb.AppendLine("")
iandamsb.AppendLine("Current name:" & txtCurrentName.Text)
iandamsb.AppendLine("New name:" & txtNewName.Text)
iandamsb.AppendLine("New username:" & txtNewUsername.Text)
iandamsb.AppendLine("Applications:" & txtOtherApplications.Text)
Dim iandambody As String = iandamsb.ToString
SendMail(txtRequesterEmail.Text, "ayockel#mydomain.com", "Name Change Request - " & txtCurrentName.Text, iandambody)
End Sub
It works just fine, however it is sending two emails instead of one. Can anyone figure out why it's sending a duplicate?
I would venture to guess that you have the button click event bound twice: once through an OnClick attribute in the markup:
<asp:Button OnClick="btnSubmit_Click" runat="server" ... />
and then again through the code-behind via Handles:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs)
Handles btnSubmit.Click
I would remove one of them if that's the case. I would keep the latter so you know that the btnSubmit_Click event is properly wired at compile time.
A discussion of this issue.

Getting previous page visited

I'm trying to get thee previous page visited in ASP.NET using VB.NET using the following code:
Partial Class _Default Inherits Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If (Request.UrlReferrer <> Nothing) Then
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
Else
lblUsername.Text = "Welcome, Guest"
End If
End If
End Sub
End Class
I get this error:
Object reference not set to an instance of an object.
at:
Dim previousPage As String = Page.Request.UrlReferrer.ToString
What I want to do is get the previous page visited so I can get a session variable.
Try This code.
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If (Request.UrlReferrer <> Nothing) Then
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
End If
Else
lblUsername.Text = "Welcome, Guest"
End If
End Sub
End Class
Unsure what you are trying to do but while its easy enough to answer your specific question, you should take a step back and review why you are doing things that way.
It seems you are trying to control flow based on some authentication. If so, consider ASP.Net Forms Authentication +/- Login Controls. You can "plug" this architecture into your existing auth mechanism (meaning you don't have to uproot your existing stuff to implement it).
(If you still want to reinvent the wheel) Consider cookies instead of trying to figure out "where the user came from" prior to landing on "this" page - both of which can vary by x - the more web pages your web site has or will have, you'll have more spaghetti.

how to access controls from class files in app code

How to access controls from class files in app code?
Markup:
<%# Page Language="vb" AutoEventWireup="false" Inherits="shoppingCart1.ShoppingPage" CodeFile="ShoppingPage.aspx.vb" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>ShoppingPage</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server" name="Form1">
<TABLE id="tblShopping" style="FONT-SIZE:10pt;FONT-FAMILY:verdana" borderColor="black"
width="100%" cellSpacing="0" cellPadding="0" border="1" runat="server">
<tr style="FONT-SIZE:10pt;FONT-FAMILY:verdana;color:white;background-color:#336699;font-weight:bold;">
<td colspan="4">PRODUCT LIST</td>
</tr>
<tr>
***<td id="cellshoping" runat="server" colspan="4" width="100%"></td>***
</tr>
<tr>
</tr>
</TABLE>
</form>
</body>
</HTML>
ShoppingCart.vb In App_Code Folder
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ShoppingCart
Public Sub bindData()
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim objDA As SqlDataAdapter
Dim myRow As SqlDataReader
Dim comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
myRow = comd.ExecuteReader()
Dim strRowGen As String = ""
While myRow.Read()
strRowGen = strRowGen & "<TR>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
strRowGen = strRowGen & "</TR>"
**cellshoping**.InnerHtml = strRowGen
End While
End Sub
End Class
I get an error at cellshoping.InnerHtml "cellshoping is not declared"...how to access user controls from class files in app code ??
ADDED ASPX CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Namespace shoppingCart1
Partial Class ShoppingPage
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
Protected WithEvents Label3 As System.Web.UI.WebControls.Label
Protected WithEvents txtNK As System.Web.UI.WebControls.TextBox
Protected WithEvents txtCF As System.Web.UI.WebControls.TextBox
Protected WithEvents txtHA As System.Web.UI.WebControls.TextBox
Protected WithEvents dtGrdProducts As System.Web.UI.WebControls.DataGrid
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Load data by calling function bindData()
Dim sCart = New ShoppingCart
If Not Page.IsPostBack Then
cellshoping.InnerHtml = sCart.bindData()
End If
Dim strQty As Integer
Dim proId As String
Dim delId As String
delId = Request.QueryString("delItemId")
proId = Request.QueryString("itemId")
'------ Following portion act as controller where code is written as
'------ per the action from the request of the pages like Add To Cart,
'------ Update Cart & Delete Cart
strQty = 1
If Request.QueryString("Actn") <> "" Then
If Request.QueryString("Actn").Equals("Add") Then
If Request.QueryString("itemId") <> "" Then
AddToSession(proId, strQty)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Del") Then
If Request.QueryString("delItemId") <> "" Then
Session.Remove(delId)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Update") Then
If Request.QueryString("itemUpId") <> "" And Request.QueryString("quantity") <> "" Then
If IsNumeric(Request.QueryString("itemUpId")) Then
updateCart(Request.QueryString("itemUpId"), Request.QueryString("quantity"))
Response.Redirect("./ShoppingCart.aspx")
Else
Response.Redirect("./ShoppingCart.aspx")
End If
End If
End If
End If
End Sub
Private Sub AddToSession(ByVal strProduct As String, ByVal intQty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(Session(strProduct)) + intQty)
Else
Session.Add(strProduct, intQty)
End If
End Sub
Private Sub updateCart(ByVal strProduct As String, ByVal qty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(qty))
End If
End Sub
End Class
End Namespace
Assuming that the ShoppingCart class is referenced somewhere in the page's code-behind and the BindData() method is called from that code, you have a few choices:
1) Pass a reference to the page to the shopping cart's bind data method.
2) Return the data from the BindData() method to the page so that it can update the data in the page appropriately.
3) You could access HttpContext.Current.Handler and cast that to an instance of your page.
My recommendation, especially if you want to use the class in other pages, is to either create an interface that has a method that can be used to update the data and use options 1 or 3, or implement option 2.
Here is an example of how you would change the code to implement and interface.
The interface:
Public Interface IShoppingCartPage
Sub UpdateData(sCartContents As String)
End Interface
The page codebeghind (partial):
Public Class ShoppingPage
Implements IShoppingCartPage
Public Sub UpdateData(sCartContents As String) Implements IShoppingCartPage.UpdateData
cellshopping.innerHtml = sCartContents
End Sub
End Class
And finally, the modified shopping cart class (note the use of the stringbuilder class, which will be much more efficient than the string concat in the question):
Public Class ShoppingCart
Public Sub bindData(oPage As IShoppingCartPage)
Using con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
Using oReader As SqlDataReader = comd.ExecuteReader()
Dim sbHTML As New System.Text.StringBuilder(5000)
While oReader.Read()
sbHTML.Append("<TR>")
sbHTML.Append("<TD>").Append(oReader.GetValue(0)).Append("</TD>")
sbHTML.Append("<TD>").Append(oReader.GetValue(1)).Append("</TD>")
sbHTML.Append("<TD>").Append(oReader.GetValue(2)).Append("</TD>")
sbHTML.Append("<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=").Append(oReader.GetValue(0)).Append("';document.Form1.submit();"">Add To Cart</TD>")
sbHTML.Append("</TR>")
End While
oPage.UpdateData(sbHTML.ToString())
End Using
End Using
con.Close()
End Using
End Sub
End Class
Why not have your method return a string?
Public Function bindData() as String
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim objDA As SqlDataAdapter
Dim myRow As SqlDataReader
Dim comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
myRow = comd.ExecuteReader()
Dim strRowGen As String = ""
While myRow.Read()
strRowGen = strRowGen & "<TR>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
strRowGen = strRowGen & "</TR>"
End While
Return strRowGen
End Sub
Then you can call it from your page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'Set innerHtml here
'cellshoping.InnerHtml = ShoppingCart.bindData()
End Sub

User enters code into TextBox, code gets added to URL (using session)

I'm using ASP.net 4.0 VB :)
I am using a session variable to add a user entered code into the url of each page. I can get the code to show up at the end of the page's URL that my textbox is on, but what do I add to every page to make sure that the session stays at the end of every URL that person visits during their session? This is the code from the page that the user enters their user code.
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
Session("IB") = IBTextBox.Text
Dim IB As String = Session("IB")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProductID.Value = Request.QueryString("id")
If Session("IB") Is Nothing Then
tab4.Visible = "False"
Else
tab4.Visible = "True"
End If
End Sub
This is what I have in the page load of one of the other pages. What else do I add to make sure that variable is added to the URL of that page?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IB As String
IB = Session("IB")
End Sub
string url = Request.Url.ToString();
string newUrl = url + url.Contains("?") ? "&" : "?" + "ib=" + Server.UrlEncode(IBTextBox.Text);
Response.Redirect(newUrl);
return;
The approach I might use would be to create a base page class that all of your pages can inherit. The base page would then inherit the System.Web.UI.Page.
Within your base page class, create a property for IB and also handle the page load event.
In that event, check if the QueryString has the IB parameter in it. If it does, set the property to the value in the parameter.
Private _IB As String
Public Property IB() As String
Get
Return _IB
End Get
Set(ByVal value As String)
_IB = value
End Set
End Property
Public Function GetIB(ByVal url As String) As String
If Not(_IB = String.Empty) Then
If (url.Contains("?")) Then
Return "&IB=" & _IB
Else
Return url & "?IB=" & _IB
End If
Else
Return url
End If
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (String.IsNullOrEmpty(Request.QueryString("IB"))) Then
_IB = Request.QueryString("IB")
End If
End Sub
Finally in your markup you would need to place something like the following at the end of all of your links:
next page
I threw this code into the Master Page to make sure that every page knows whether or not the Session is there. Thanks for all the help everyone!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("IB") Is Nothing Then
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
Else
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name")
End If
End Sub

Jqmodal isn't working in the Updatepanel

I have a method named raise_alarm() which, show a message box based on jquery. But when I call this method from an event of a control(such as submit button) which is inside of Updatepanel, it isn't working. Related codes are below. How can I fix it?
Public Sub Raise_Alarm(ByVal p_Page As Page, ByVal p_Message As String, Optional ByVal p_IsError As Boolean = True)
Dim strScript As String
strScript = "$(function() { Mesaj('" & p_Message & "'); });" & ControlChars.NewLine
p_Page.ClientScript.RegisterStartupScript(p_Page.GetType(), "alert", strScript, True)
end sub
Private Sub dtlQuestion_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dtlQuestion.ItemCommand
If Not User.Identity.IsAuthenticated Then
Raise_Alarm(Me, "Giriş Yapmadan Oy Veremezsiniz")
Exit Sub
End If
end sub
You have to use ScriptManager instead of p_Page.ClientScript.
EDIT : Example. I replaced p_Page.ClientScript by ScriptManager in your code.
Public Sub Raise_Alarm(ByVal p_Page As Page, ByVal p_Message As String, Optional ByVal p_IsError As Boolean = True)
Dim strScript As String
strScript = "$(function() { Mesaj('" & p_Message & "'); });" & ControlChars.NewLine
ScriptManager.RegisterStartupScript(p_Page.GetType(), "alert", strScript, True)
end sub
Private Sub dtlQuestion_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dtlQuestion.ItemCommand
If Not User.Identity.IsAuthenticated Then
Raise_Alarm(Me, "Giriş Yapmadan Oy Veremezsiniz")
Exit Sub
End If
end sub
ClientScript is not ajax enabled, ScriptManager knows how to deal with partial postbacks. Please have a quick look at this article on msdn.

Resources