How to use class code of vb.net in asp.net - asp.net

I'm having trouble with using my vb.net code in asp.net webpage.
<%# Page Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="WebForm1.aspx.vb" Inherits="Banking_Application.WebForm1" CodeFile="~/WebForm1.aspx.vb" %>
class name is WebForm1. I've written code in a separate file and I want to use it in page.
Like
<% Dim total As Integer
Dim val As tests.WebForm1
val = New tests.WebForm1
total = val.TotalBranches()
total.ToString()
%>
I'm new to vb.net and asp.net.
All suggestions are welcome.
Thanks!

Well first of all i need to clarify a few things for you:
in Asp.net, you can embed code in your aspx page using <% %> code block, or write it in a separate file and use it from there.
in your page declaration, you specify the code behind of your page using the CodeBehind= attribute, so if you want to place your code in WebForm1.vb, your page declaration should include CodeBehind="WebForm1.vb" .
note: CodeFile="~/WebForm1.aspx.vb" is not needed.
the structure of the code behind for you aspx page, should look like that:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Function test1()
Return "test"
End Function
End Class
and you can add more functions as needed. in the example above, i have added a function called test1 for the purpose of this example.
now, after you have created your code behind in the correct structure, you can call its methods from the aspx page as if it was the same page:
<% =test1()
%>
this will return "test" as specified by the function in code behind.
you do not need to instantiate the class.

I think you are missing what is happening with the mechanics of asp.net.
You either:
Write code directly in the aspx page (within the html)
Or, you wrtie code in the code behind page... your WebForm1.aspx.vb page. From the code behind page, you can access and manipulate the server controls that is on the aspx (html) side...

Related

Getting asp.net user control to emit SCRIPT block only once if needed

I'm seeking advice on how to best encapsulate this HTML markup and behavior for extensive reuse.
I've developed a working version of some "context sensitive" help on a given .aspx page that uses the qTip2 plugin for jQuery ("squeezed up" here for completeness for the question):
$('a.myMore[title]').qtip({
content: { title: { button: true } }
, style: { classes: 'qtip-youtube myCustomClass' }
, position: { target: 'mouse', adjust: { x: 5, y: 5} }
, show: { effect: function() { $(this).fadeTo(500, 1); } }
, events:{hide:function(event, api) {if (event.originalEvent.type !== 'click') return false;}}
});
Here is a sample of the the markup operated upon by the plugin above that I'd like to encapsulate:
<a class="myMore" href="#" title='Text here will be displayed by a jQuery plugin called qTip2'>
<img src='../images/icon/info1.png' alt='?' />
</a>
This is in an older environment of Visual Studio 2008 webforms using VB.Net. One thread on SO expressed my need very well - see MVC3 Razor views - but the only encapsulation approach I can think of is writing an ASP.Net web user control (.ascx) to dump out the HTML I need. I envision being able to sprinkle something like this throughout my .aspx pages:
<qTipH:qTipHelper Title="Here is some content for the qTip." runat="server" />
Am I on the right track given the "old-ish" environment in which I have to work?
I started in on writing this control and immediately noticed there is no title attribute for any of these server controls - <asp:HyperLink nor <asp:ImageButton nor <asp:LinkButton. I don't think the code-behind of the user control can inject the title attribute text into a standard HTML <a> tag.
I think I know what I need rendered but I'm looking for advice on the best approach. Thanks.
EDIT - UPDATE:
So here is my .ascx file I came up with:
<%# Control Language="vb" AutoEventWireup="false"
CodeBehind="qTipHelper.ascx.vb"
Inherits="myProjectName.qTipHelper" %>
<asp:HyperLink ID="HyperLink1" runat="server" CssClass="myMore"></asp:HyperLink>
I discovered that any "missing" attributes like "title" can be handled by the following code-behind which adds to the Attributes collection of the control:
Public Partial Class qTipHelper
Inherits System.Web.UI.UserControl
Public Title As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Title Is Nothing OrElse Title = "" Then
Visible = False
Else
Dim encodedTitle As String = Server.HtmlEncode(Title)
HyperLink1.Attributes.Add("title", encodedTitle)
HyperLink1.Attributes.Add("href", "#")
HyperLink1.ImageUrl = "../images/icon/info1.png"
End If
End Sub
End Class
On my invoking page(s), I added this:
<%# Register TagPrefix="qTip" TagName="qTipHelper" Src="~/UserControls/qTipHelper.ascx" %>
and then to spit out the HTML, I added this:
<qTip:qTipHelper runat="server" title="grist for the mill courtesy of qTip" >
</qTip:qTipHelper>
Is there a coding technique that could be added to the user control that would emit one Javascript script block at the bottom of the page (assuming that one or more tags for qTipHelper were present in the HTML above)?
In retrospect, this is weird question (I think because I never had to do anything like this before)...
Anyway, I simply collected all my current uses of qtip in a single Javascript file which I reference at the bottom of each .aspx page that uses it like this:
<script type="text/javascript" src="<%= ResolveClientUrl("~/js/qTipCode.js") %>"></script>
So, this boils down to:
1. writing a single user control
2. registering the user control on .aspx content pages that will need it
3. sprinkling the .aspx content page with the user control tag whereever it is needed
4. adding the script tag to point to the qtip Javascript file
5. ensuring that the selectors in the jQuery "match up" with the HTML markup on the page
I hope this helps someone else. I have learned alot about new stuff trying this.

Why can't I add a control the page's header from the an inline ASPX code nugget?

Why can't I add a control the page's header from the an inline ASPX code nugget? It works from the code behind.
The markup just doesn't get added to the page.
Is it the page life cycle?
In aspx page:
<%
StyleSheet.AddToHeader(Page, New List(Of String)({
"~/CSS/bootstrap.min.css",
"~/CSS/skin.css"
}))
%>
Imports Microsoft.VisualBasic
Imports System.Web.UI
Public Class StyleSheet
Public Shared Sub AddToHeader(ByRef currentPage As Page, ByVal pathList As List(Of String))
For Each singlePath In pathList
Dim lineBreak As New Literal()
Dim stylesheet As New HtmlLink()
lineBreak.Text = Environment.NewLine
stylesheet.Attributes.Add("rel", "stylesheet")
stylesheet.Attributes.Add("type", "text/css")
stylesheet.Href = currentPage.ResolveUrl(singlePath)
currentPage.Header.Controls.Add(lineBreak)
currentPage.Header.Controls.Add(stylesheet)
Next
End Sub
End Class
The code that is executed inline (inside <% and %> ) is done while it is streaming to the client computer.
You cannot do that and expect the header to be updated because you are altering the object AFTER it has performed it's "RenderControl" internal routine.
Most code behind happens before the rendering takes place which is why you can do it behind the scenes without issue.

find control on page using vb.net

I'm using the FindControl function to look for a control on the page. It seems super simple and straight forward on MSDN but I can't get it to find the control. The page I'm using has a MasterPageFile that prepends more to the id that I give the contorl in the aspx file. A simple example that isn't working:
aspx page
<%# Page Title="Inventory Control Test" Language="VB" AutoEventWireup="false" MasterPageFile="~/Site.master" CodeFile="Default2.aspx.vb" Inherits="Sales_ajaxTest_Default2" %>
<asp:Content ID="conHead" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="conBody" ContentPlaceHolderID="MainBody" Runat="Server">
<asp:Button ID="saveAllBtn" runat="server" Text="Save All" />
</asp:Content>
code behind
Partial Class Sales_ajaxTest_Default2
Inherits System.Web.UI.Page
Protected Sub saveAllBtn_Click(sender As Object, e As System.EventArgs) Handles saveAllBtn.Click
Dim myControl1 As Control = FindControl("ctl00_MainBody_saveAllBtn")
If (Not myControl1 Is Nothing) Then
MsgBox("Control ID is : " & myControl1.ID)
Else
'Response.Write("Control not found.....")
MsgBox("Control not found.....")
End If
End Sub
End Class
I get that msgbox isn't a web thing I'm just using it for this example.
If i use "saveAllBtn", which is the id given to the control, in the FindControl I get "control not found". If I try this, on a stand alone page without a masterpage it works fine.
If I inspect the element using chrome I find that the ID of the button has been changed to "ctl00_MainBody_saveAllBtn" but if I use that in the FindControl I still get "control not found"
When you use FindControl you would specify the "server ID" (what you named it) of the control, not the final rendered "client ID" of the control. ex:
Dim myControl as Control = MainBody.FindControl("saveAllBtn")
However, in your specific example, since you are in the saveAllBtn.Click event, the control you are looking for is actually the sender parameter (because you clicked on that button to trigger the event you are in) ex:
Dim myControl as Button = CType(sender, Button)
If you just want to find saveAllBtn control, wweicker's second method using CType(sender, Button) is the prefer one.
However, if you want to find other control by name, you cannot use just FindControl. You need to find the control recursively, because it is nested inside other controls.
Here is the helper method -
Protected Sub saveAllBtn_Click(sender As Object, e As EventArgs)
Dim button = TryCast(FindControlRecursive(Me.Page, "saveAllBtn"), Button)
End Sub
Public Shared Function FindControlRecursive(root As Control, id As String) As Control
If root.ID = id Then
Return root
End If
Return root.Controls.Cast(Of Control)().[Select](Function(c) FindControlRecursive(c, id)).FirstOrDefault(Function(c) c IsNot Nothing)
End Function
Note: My VB code might be a bite weird, because I wrote in C# and converted to VB using converter.
FindControl does not work recursively. You must start at one point (Me, for example), and if that is not the control your looking for, search the Controls collection of your starting point. And so forth.

Single javascript function for multiple web pages

I have around 40 aspx pages in my website.
I want to use a javascript function which needs to be called when any of the 40 pages is loaded.
something like
I could have this function in the "head" section of each of the 40 aspx pages and then call in the body onload event. But I would like to have this function at a single place.
This is an existing app so I cannot create a master page and have all the pages derive from it.
Any ideas?
You will need to put the function in a .js file and call from your pages, but you will need to link to the script in all your 40 pages, since you can't add master page.
You can create a base class that it will be inherited by all these pages and write the logic of inserting javascript there.
So, do something like it:
Create a base class:
[Serializable]
public class RequiresFunctionBasePage : System.Web.UI.Page
{
public RequiresFunctionBasePage()
{
this.Load+= new delegate
{
this.ClientScript.RegisterClientScriptInclude("yourScript", "http://yoursite.com/yourJs.js");
this.ClientScript.RegisterStartupScript(this.GetType(),
"functionOnload", "functionName();", true);
}
}
}
And into your aspx codebehind:
public partial class yourPageNameGoesHere : RequiresFunctionBasePage
{
(...)
I suppose if you wanted to make it difficult/elegant, you could make an HttpModule that injects the script. That way it's only in one place and you can wire it up in the web.config.
Here's a sample httpModule
Public Class JavascriptInjector
Implements IHttpModule
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.PreRequestHandlerExecute, AddressOf PreRequestHandlerExecute
End Sub
Private Sub PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
Dim myPage = TryCast(HttpContext.Current.CurrentHandler, Page)
If myPage Is Nothing Then Exit Sub
AddHandler myPage.InitComplete, AddressOf Page_Init
End Sub
Sub Page_Init()
Dim myPage = TryCast(HttpContext.Current.CurrentHandler, Page)
If myPage Is Nothing Then Exit Sub
Dim path = myPage.ResolveUrl("~/js/jscript.js")
myPage.ClientScript.RegisterClientScriptInclude(myPage.GetType, "common", path)
End Sub
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
End Sub
End Class
Here's an entry in the web.config
<httpModules>
<add name="javascriptInjector" type="JavascriptInjector"/>
</httpModules>
You will need to modify the masterpage to include a new JS file with your new function or place your JS function in one of the JS files already included in the masterpage.
For a fully client side solution you could create a javascript file (possibly named script.js) that you link to from the head of your master page. In that file put your function.
So, the javascript in the script.js file would be something like this:
function SampleFunction(text) {
alert(text);
// or whatever code you want
}
and then in the head of your pages
<script type="text/javascript" src="script.js"></script>
and then your onload can be
onload="SampleFunction('hi there');"
have fun :)
robb

Setting page title from # Page directive in ASP.NET using master pages

I am using master pages and am having trouble setting page titles from the # Page directive. All of my classes inherit from a class myPage which inherits from the ASP.NET System.Web.UI.Page class. Please Note: I have runat="server" set in my master page's head tag.
Here's what my # Page directives look like for the file test.aspx.vb:
<%# Page language="VB" MasterPageFile="~/MainMaster.master"
autoeventwireup="false" CodeFile="test.aspx.vb"
Inherits="test" Title="test" %>
Here's what test.aspx.vb looks like:
Partial Class test
Inherits myPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
This is what my master file, MainMaster.master, looks like:
<%# Master Language="VB" CodeFile="MainMaster.master.vb" Inherits="MainMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>untitled</title>
</head>
...
Now, when you go to view test.aspx in a browser you'd expect to see the title 'test'. but instead you will see 'untitled' as per the master page. Through trial and error, I modified the test class to inherit from System.Web.UI.Page directly, instead of myPage like this:
Partial Class test
Inherits Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
and everything worked just fine. Why would my pages being children of myPage instead of System.Web.UI.Page prevent the title from being set correctly in the # Page directive?
I realize that I could just set the page titles programmatically through the Page_Load methods in every page, but I'd rather do it in the # Page directives in the .aspx files.
This is a very weird and frustrating problem, and I'm at a loss!
Thanks!!!
I thank everyone for their help; I have found a solution. The problem was that the myPage class had a property for Title, but in the Set part of the property was not passing the changes on to Page.Title as it should have been.
A one line change fixed my problem :)
What methods do you have in your base page (myPage.vb).
If you are overriding any of the default methods, are you calling the base versions of those pages?
in C# I'd have something like this:
protected override void OnInit(EventArgs e)
{
// Do my custom processing.
// Don't forget to call base OnInit here:
base.OnInit(e);
}
If you don't call these methods, then the events that happen in them for you (like wiring up the masterpage's title) won't fire.
I have a very similar set up to you. I have content pages inheriting from a custom base page which is itself inheriting from page. I am not having any issues with the title being set on the aspx and being shown in the browser. The only difference I see between my code and yours is my master page has the autoeventwireup property where your master page does not, and also your master page has a property called codefile and mine has codebehind.
Content Page:
<%# Page Title="Login to Application X" Language="vb" AutoEventWireup="false" MasterPageFile="~/masterpages/mymasterpage.Master"
CodeBehind="login.aspx.vb" Inherits=".login" %>
Master Page:
<%# Master Language="VB" AutoEventWireup="false" CodeBehind="mymasterpage.master.vb"
Inherits=".mymasterpage" %>

Resources