Using ASP.NET Code-Behind Without Visual Studio.NET

by John Peterson


Introduction

I'm sure you've probably heard (since I've done nothing but talk about it) that we recently went to San Jose to put on our very own ASP.NET Developer Conference & Expo. While we were there, we talked to a number of developers and got a good feel for what the attendees were most looking forward to in ASP.NET. One of the things that kept coming up was the ability to use code-behind to separate the display and layout of an ASP.NET page from it's code and application logic.

Apparently some developers worry about what their sites look like and as a result they actually work with a graphic designer or layout artist (I'm not up on the politically correct title) to get it looking spiffy... who knew!  ;)   This is where code-behind really is a godsend. You just send the graphics person the Web Form portion of your page and they work with that. They never get to see (or mess with and break) the code that you've spent days working to get just right.

In Visual Studio.NET (VS.NET), this magic is all done for you. Now here's the rub... what if you don't have VS.NET? We've always maintained that while all the fancy tools are nice and might make you more productive, you don't need them to develop working solutions using ASP or ASP.NET. An email from one show attendee brought this whole topic to a head... here's an excerpt:

hey, john - i was in the San Jose developer's conference, i believe i got a chance to talk to you there a bit...i was searching through asp101 and not quite able to come up with an answer to a question that's bothering me, maybe it's so obvious no one is answering it, but i can't quite work through it alone.

i understand that there is a way to run a code-behind page inheriting from a class in a compiled DLL, yes? from what i've read visual studio .net does this 'automagically', but i can't find any explanation as to what the magic is, really. i've got VS on order, but anyway i'd like to understand how this stuff works with or without it.

To address the email and since I don't like to be proven wrong... here's how you can implement code-behind using just a plain old text editor and the tools included in the .NET Framework... no VS.NET required!

What Code-Behind Looks Like in Visual Studio.NET

Before we start, let me take this opportunity to illustrate what we're talking about. (I know I said no VS.NET, but it's just for illustration.)

I've fired off VS.NET and added a blank VB Web Form to my project (named boringly enough WebForm1.aspx). Next I add a button (named Button1) to the page. Here's what it looks like:


Figure 1

We're still basically in that same one file. When I click the button to add code to it, all of a sudden, a new file (named WebForm1.aspx.vb after our WebForm1.aspx) opens and VS.NET drops me into it in order to write the code for the button's click event.


Figure 2

Here are the code listings for the two resulting files:

WebForm1.aspx

<%@ Page Language="vb" AutoEventWireup="false"

  Codebehind="WebForm1.aspx.vb" Inherits="WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>WebForm1 Code-Behind Test</title>

    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name=vs_defaultClientScript content="JavaScript">

    <meta name=vs_targetSchema
      content="http://schemas.microsoft.com/intellisense/ie5">
  </head>
  <body MS_POSITIONING="GridLayout">

    <form id="Form1" method="post" runat="server">

      <asp:Button id="Button1" runat="server" Text="Button">
      </asp:Button>
    </form>

  </body>
</html>

WebForm1.aspx.vb

Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> _
      Private Sub InitializeComponent()

    End Sub

    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
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Button1.Click
        ' Do Something When The Button Is Clicked!
    End Sub
End Class

Once I have VS.NET build my project and request it from a browser, whatever I type in the button click event handler (Button1_Click) in WebForm1.aspx.vb will execute when the button on WebForm1.aspx is clicked. Let's look at how this is accomplished.

Hot Wiring Our Own Code-Behind Page

Just looking at the listings above... most of this stuff has nothing to do with the actual code-behind process. The obvious command to investigate is Codebehind="WebForm1.aspx.vb". Oddly enough however this doesn't do anything in ASP.NET... it's there only so VS.NET can find the source code! Let me illustrate.

I stripped down the above files and added a label control. I also added a command, which modifies the label, to the button click event handler (in the code-behind file) so we can tell when the two files are communicating and have some indication that the event handler is actually running. As a final step I renamed the files and classes to WebForm2 to prevent it from working because of anything VS.NET does behind the scenes... we're trying to accomplish this on our own! Here are the resulting 2 file listings:

WebForm2.aspx

<%@ Page Language="vb" AutoEventWireup="false"
  Codebehind="WebForm2.aspx.vb" Inherits="WebForm2"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>WebForm2 Code-Behind Test</title>
  </head>
  <body>

    <form id="Form1" method="post" runat="server">
	  <asp:Button id="Button1" runat="server" Text="Button">

	  </asp:Button>
	  <br />
	  <br />
	  <asp:Label id="Label1" runat="server">Label</asp:Label>

    </form>
  </body>
</html>

WebForm2.aspx.vb

Public Class WebForm2
    Inherits System.Web.UI.Page
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label

    Private Sub Button1_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Button1.Click

        Label1.Text = "I was clicked at: " & System.DateTime.Now

    End Sub
End Class

Naturally that would be too easy... when you try and run WebForm2.aspx, you'll get an error something like this:

Parser Error Message: Could not load type 'WebForm2'.

Don't worry... all is not lost. The problem is simply that it can't find the class we define in our code-behind file. Normally VS.NET will automatically compile the .vb file into a .dll and place it in your application's /bin directory. Since we're not using VS.NET, it wasn't compiled and the application can't find the appropriate class. There are two solutions - compile it manually or tell the .aspx file where to find the .vb source file.

Compiling it manually is really pretty easy. The command will look something like this:

vbc /t:library /out:bin\WebForm2.dll /r:System.dll /r:System.Web.dll WebForm2.aspx.vb

I'm not going to go into all the compiler options, but basically we're taking WebForm2.aspx.vb and compiling it into a dll named WebForm2.dll and placing it in the application's /bin directory.

This option is the better approach if you need complete control over your compiler options or if you will be distributing the application without the .vb source files. Being the lazy type, I tend to go for option 2... check out this code listing:

WebForm3.aspx

<%@ Page Language="vb" AutoEventWireup="false"
  Src="WebForm2.aspx.vb" Inherits="WebForm2"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>WebForm3 Code-Behind Test</title>
  </head>
  <body>

    <form id="Form1" method="post" runat="server">
	  <asp:Button id="Button1" runat="server" Text="Button">

	  </asp:Button>
	  <br />
	  <br />
	  <asp:Label id="Label1" runat="server">Label</asp:Label>

    </form>
  </body>
</html>

Looks just like the last one doesn't it... well not quite... notice that instead of the Codebehind="WebForm2.aspx.vb" we now have Src="WebForm2.aspx.vb". While Codebehind doesn't mean anything to ASP.NET, Src (short for source) does and the code-behind file will compile on the fly just like the .aspx file.

Note: Don't worry... you're not missing a file... I've got WebForm3.aspx running off the same code-behind file as WebForm2.aspx since the two .vb files would be identical anyway.

Some Final Notes

In order for .NET to find your classes, make sure your compiled files are stored in the /bin directory off the root of your application. You need to make sure you've set your directory up as an IIS application or else ASP.NET will go up the tree until it finds one and end up at the /bin directory of the root application if it doesn't find one sooner.

Those of you using VS.NET might have noticed my Inherits statements are short a project name. That's because VS.NET creates a separate namespace for each project it creates. It's easy enough to do just use the Namespace command, but that's beyond the scope of this article. I'm only mentioning it so you don't panic when you see an inherits line that looks like this:

<%@ Page Language="vb" Inherits="ProjectName.WebForm2"%>

Wrap Up

So to sum everything up... all it really takes to do code-behind is one little inherits attribute in your page declaration line specifying the name of the class you want to inherit. If you're willing to precompile your classes into .dll files, that's where it stops. If you're lazy like me or like the "edit and run" simplicity that classic ASP gave you, add a src attribute pointed at your code-behind file and ASP.NET will compile it for you. That's really all there is to it.

If you don't want to copy and paste the code listings, you can get all 5 files in zip file format below.


Update: Separating Code-Behind and Web Form Files

A reader recently wrote:

Hi John,

I've read several of your articles, and I think you are the right person for my question.

Here is my case:

By default, code behind files (*.cs) and *.aspx files are located in the same folder. I want to separate my code behind files to a different folder. Is there any way to make it work?

If you can, please help.

Thank you in advance,
An

Well it's actually quite easy... just specify the full or relative virtual path to your code-behind file in your Web Form and you should be good to go. Continuing with the example used in the article, if you moved all your .vb files to the /codebehind folder, this script should find them:

WebForm4.aspx

<%@ Page Language="vb" AutoEventWireup="false"
  Src="/codebehind/WebForm2.aspx.vb" Inherits="WebForm2"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>WebForm3 Code-Behind Test</title>
  </head>
  <body>

    <form id="Form1" method="post" runat="server">
	  <asp:Button id="Button1" runat="server" Text="Button">

	  </asp:Button>
	  <br />
	  <br />
	  <asp:Label id="Label1" runat="server">Label</asp:Label>

    </form>
  </body>
</html>

Other Code-Behind Resources On The Web



About the Author

From ASP101

Articles originally posted on ASP101.com

Downloads

Comments

  • de kleurrijke vreugde in mijn leven als gevolg van Beats By Dr Dre Studio

    Posted by mrswanzi on 06/06/2013 03:53pm

    [url=http://beatssolokopen.weebly.com/]beats solo kopen[/url] Terwijl ze konden misschien niet klein, oordopjes hebben meestal matig chauffeurs. beats monster by dre vakantie oordopjes verklaren grote driver exploitanten, en gecentreerd in de buurt van de gunstige koper reactie, lijkt de grote automobilisten dimensie rekeningen voor het gebruik van de matige regelmaat reactie. Zelfs als uw oordopjes zijn geweldig, moet je echt de tevreden is slecht een oordopjes waardeloos zijn. Deze oordopjes komen productie van het gebruik van de vele monster headphones isoleren oordopjes truc maten en soorten om de mogelijkheid om een beroep op iedereen te bezitten. bezit vermeld dat, even bewust waarom deze oordopjes factoren zou kunnen ongeschikt iedereen. [url=http://koptelefoon-monsterbeats.webspawner.com/]beats by dre kopen[/url] Dt zorgt voor verlies aan helderheid in het geluid en zorgt er voor dat bepaalde toenen wegvallen. De meeste koptelefoons zijn niet trouw aan de dynamiek, de bas en de frequenties van de originele opnames. Hierdoor maakt de muziek niet de impact bij de luisteraard waar de artisten naar streven. De oordoppen produceren niet alleen een superieure geluidskwaliteit, maar zijn ook comfortabel om voor langere tijd te dragen. De oordoppen worden geleverd met ultra-zachte ademende en zachte oorkussens die ervoor zorgen dat luisteraars koel en comfortabel, zelfs zelfs wanneer je uren lang muziek luisterd blijven de beats by dre comfortabel zitten. [url=http://koptelefoon-monsterbeats.tumblr.com/]beats by dre[/url] De Beats goederen op te bouwen door Dr Dre heeft vele soorten hoofdtelefoons. Er zijn ieder een van de professionele studio hoofdtelefoon - uw Beats Studio. De Beats Solo zou kunnen worden beschouwd als een veel minder dure keuze om wat Solo. ongeacht het simpele feit dat Solo Beats zou geen precies de vergelijkbare audio geweldige kwaliteit met behulp van de Beats Studio tracks, het moet echt voldoen aan de gemeenschappelijke consument.

    Reply
  • where you can steal the cheapest clarisonic mia

    Posted by iouwanzi on 06/06/2013 02:57pm

    [url=http://www.australiaclarisonic.com/]clarisonic brush[/url] Le courant autres avantages est la taxe avec la hausse des températures internationales. Les secondes (optimales avec 10!) après que commutation autour de la conception et de style, du sculpter va à son pouvoir alerte aux États-Unis qu’il est prêt à devenir employé. C’est vraiment un gain de temps grave de souche, même si professionnellement j’ai réellement en aucune façon utilisent mon fer plat personnel chaque fois que je suis rempli à l’intérieur. [url=http://www.australiaclarisonic.com/clarisonic-pro]clarisonic pro[/url] Mon conjoint et moi posséder prolongée (pratique pour vous aider mes coudes personnels) mince, okay, colorés mais aussi soulignée, nui chevelure. Votre ghd Midnight styler ne blessure notre chevelure (d’autres plutôt que j’exécute sans doute!)#) en quelque sorte. Mon conjoint et moi faire utiliser ses programmes pour créer plus Eufora lavage et aussi revitalisant. Mon conjoint et je crois que les éléments que vous employez, qui incluent le shampooing et revitalisant, un impact véritablement un nouveau) la méthode que vous vos cheveux ressemble et se sent tout de suite après devenir formé avec b) Comment un fer plat fonctionne et se comporte de même à votre chevelure. [url=http://www.australiaclarisonic.com/]clarisonic australia[/url] N’importe quel moment une personne prise à la dernière mode en mode et beauté, vous réalisez vraiment que le faste et le glamour des années 20 ont tendance à être offerts. Pour sûr, hivernal sera donner stratégie vers grésillant chaud pin up en vous en fait toute cette métamorphose, vous pouvez compter sur n’importe quelle collection de ghd écarlate.Cette approche complètement nouveau petit format Styler Golden Classic ® réinventé simplement en changeant la couleur concernant la véritable redressage des disques et donc passer à travers du métal jaune pour vous à rouge foncé.

    Reply
  • Nike Aura Max+instagram, wishes you hold the color to step on your feet!

    Posted by madytreathy on 04/20/2013 12:11pm

    Recognize in 2008, if not earlier, when Nike launched winning of the independent shoe color projects, the war cry "Shoot Your Colours", "Nike PhotoiD" arrangement, [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] return has not been as avid as expected. Have in mind, 2008 Canon IXUS 80 IS Digital prankster arcade but purely 8 million pixels, Nokia, the motorized phone market-place is the at worst governorship, NikeiD was promote to color in the photos as a basis for sneakers excise color, although exciting, but does trouble some. Instagram which make this thing fun and modest, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://northernroofing.co.uk/roofins.cfm]nike free run uk[/url] released a fresh plan. That such iD can you realize pictures as instagram account shoe color, the meanwhile volunteer Nike Air Max shoes and Nike Puff Max 1, Nike Show Max 90 953 options. Interested in children's shoes, you [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] can without exception vanish into thin air's proper website photoid.Nike.com, in addition to browse other people's ingenious charge, or you can hear to upload your own instagram photo, physique your own Nike Feeling Max.

    Reply
  • The Unique Role Of Fiber In Coffee Diet?

    Posted by GoosyIdory on 01/05/2013 07:27am

    7656 madyu Though Optimum and ISO are the most popular, there are quite a few brands which can be tried out and they have received excellent reviews and ratings from various health magazines and experts. [url=http://mygreencoffeebean.net/what-are-the-benefits-of-green-coffee-bean-extract-to-me/]green coffee bean extract[/url] 4652 xndzy The company focuses on diseases affecting the back of the eye or retina, and licenses ILUVIEN from PSDV. 7466 ermqd Eat the burger with pineapple chunks. We were never meant to deny ourselves all the pleasures of life. Once you have lost a dress size, reward yourself with that dress you've always wanted to buy, but didn't think you'd look good in. Now is the time to begin getting those things rewards for all your hard work. Just don't reward yourself with food. Two stalks of celery, one cucumber, two broccoli crowns and an apple.

    Reply
  • What Are The Tannins In Coffee Diet?

    Posted by reerneNow on 01/04/2013 04:03pm

    275 exgmy Medium-density carbohydrates fruits, starchy vegetables, dairy products: These foods have more carbs per serve than the low-density carbohydrates. Therefore, their ability to increase blood sugar is greater. Since they increase blood sugar, insulin will also get secreted, which means the body will be more likely to store body fat. [url=http://mygreencoffeebean.net/what-are-the-benefits-of-green-coffee-bean-extract-to-me/]green coffee bean extract[/url] 6269 xjxqq However, her more conservative and smarter style failed to distract from her sexy curves as she did some strenuous lunges on the sand. 2128 ospxh Can you get the same results by drinking coffee? A number of studies previously found that people who drink at least five cups of coffee a day are substantially less likely to get Type 2 diabetes. Other studies have linked caffeine to weight loss and a reduced risk of metabolic syndrome. But none have shown the dramatic results of this new study. A spokeswoman said: 'We're delighted that the government is taking measures to prevent the promotion of irresponsible and unhealthy fad diets. Weight Watchers is not a diet, it's a healthy lifestyle.'She said they encourage a 'healthy and sustainable weight loss' of no more than 2lbs a week. With the fast growing numbers of people affected by obesity and obese associated illnesses, there are a great deal more obese individuals who realize they are having a troublesome time dropping the necessary amount of weight utilizing typical dietary plans and keep-fit programs. At the same time that you're overweight there are numerous health problems that develop and being seriously overweight can shorten your life. In this advanced innovative era, weight loss surgical procedures are now in great demand, which is attributable to their verified weight loss results. If you are contemplating a weight reduction surgical procedure to take care of your excessive weight problem and obesity related ailments, it's smart to look into the advantages of getting weight loss surgery.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

  • Live Event Date: August 14, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Data protection has long been considered "overhead" by many organizations in the past, many chalking it up to an insurance policy or an extended warranty you may never use. The realities of today make data protection a must-have, as we live in a data driven society. The digital assets we create, share, and collaborate with others on must be managed and protected for many purposes. Check out this upcoming eSeminar and join eVault Chief Technology …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds