Code model in Visual Studio

So far, we’ve only talked about how simple web pages are designed, and what parts the Visual Studio interface consists of. But before you start serious coding, you need to understand some basic details of the code model ASP.NET. Therefore, this article will focus on the available code use cases for programming web pages and how events can be used. ASP.NET they are linked to the code.

Visual Studio supports two models for encoding web pages:Internal text code

This model is closest to the traditional ASP model. All code and HTML markup are saved in a single file with the .aspx extension. The code is inserted into one or more script blocks. However, although the code is located inside the script block, it does not lose support for the IntelliSense function and debugging capabilities, and it is not necessary to execute it in a linear way from top to bottom (like classic ASP code). Instead, you can still respond to control events and use routines.

This model is convenient because it allows you to store everything in one place without any frills and therefore is often used to encode simple web pages.Separated code (code-behind)

This model implies creating for each web page ASP.NET two files: a markup file (.aspx) with HTML handles and control handles, and a code file (.cs) with the page source code (provided that the web page is programmed in C#). This model provides a more convenient organization scheme, allowing you to separate the user interface from program logic, which is very important when creating complex pages.

To better understand what the difference is between the models of intra-text and separated code, it doesn’t hurt to look at a simple page. The following example shows markup code for a page named WebForm1. aspx, which displays the current time in a text label and refreshes the page whenever a button is clicked in it. If you use the intrastext code model, this page will look like this:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Текущее время: " + DateTime.Now.ToLongTimeString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            <asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

The following codes for the WebForm1.aspx and WebForm1.aspx.cs files show how the same page will be divided into two parts if the separated code model is used:

HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            <asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Current time: " + DateTime.Now.ToLongTimeString();
        }
    }
}

The only real difference between the in-text code example and the separated code example is that in the latter case, the page class is no longer implicit, but instead is declared as a class containing all the page methods.

In general, the separated code model is preferable for complex pages. Although the intra-text code model is a bit more compact for small pages, as the amount of code and HTML markup increases, it becomes much easier to deal with them separately. In addition, the separated code model is conceptually cleaner because it explicitly displays the created class and imported namespaces. Finally, it also allows the web designer to improve the page layout without affecting the code written by the developer.

Linking separated code files to pages

Every page .aspx starts with the Page directive, which specifies the language for the page and says ASP.NET location of the linked code (unless embedded code is used, in which case the code is contained in the same file).

There are several ways to determine the location of linked code. In older versions ASP.NET It was common to use the Src attribute to indicate the source code, or the Inherits attribute to indicate the name of the compiled class. However, both of these features have their own individual characteristics.

For example, using the Inherits attribute, you have to pre-compile the code, which is quite tedious (and can cause problems in development teams, since the standard option is to compile each page into a separate assembly DLL). But the real problem is that both approaches force you to declare every web control you’re going to use with an instance variable. This results in a large amount of stereotyped code.

This problem can be solved by using a language tool called partial classes, which allows you to split a single class into multiple source code files. Basically, this model is the same as before, but the control declarations are moved to a separate file. As a developer, you should not be distracted by this file — on the contrary, you can simply access your web page controls by name. You probably noticed the word partial in the web page class declaration:

public partial class WebForm1 : System.Web.UI.Page
{ ... }

When there is such a part of the infrastructure, everything else is easy. To specify the class used in the page .aspx uses the Inherits attribute, and the CodeBehind attribute is used to specify the file that contains the separated code.:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

Note that Visual Studio uses a somewhat unusual naming syntax for the source code file. It contains the full name of the corresponding web page, provided with the extension .aspx and at the end followed by an extension .cs. This is just a convention to avoid the problem of creating two different types of separate code files (for example, web pages and web services) with the same name.

Linking control handles to page variables

When requesting a web page in a browser window ASP.NET first, it finds the associated code file, and then generates a variable declaration for each server control present in it (i.e., for each element that has the runat=”server” attribute).

For example, suppose there is a text field named txtInput:

<asp:TextBox ID="txtInput" runat="server" />

ASP.NET generates the following instance variable declaration for it and combines it with the page class using the” magic ” partial class mechanism:

protected System.Web.UI.TextBox txtInput;

Of course, you won’t see this ad, because it is part of the automatically generated code that the .NET compiler creates . But you will rely on it whenever you write a line of code that references the txtInput object (to read or write the property).:

txtInput.Text = "Hello."; 

To ensure that this system is working properly, use a markup file .The aspx (with control handles) and the .cs file (with source code) must be maintained in a synchronized state. Editing the names of controls in one of them using some other tool (for example, a text editor) will break the connection and make it impossible to compile the code.

By the way, you’ll notice that control variables are always declared using the protected keyword (meaning protected access). It’s all about the way in which ASP.NET uses inheritance in the web page model. There are the following levels:

  1. The Page class, which is part of the class library .NET, defines a basic set of functionality that allows a web page to serve other controls, render HTML code, and provide access to traditional ASP-style objects like Request, Response, and Session.
  2. Your separate code class (for example, WebForm1) inherits from the Page class to get this basic set of web page functionality ASP.NET.
  3. When you compile your class, ASP.NET adds some additional code to it (using the” magic ” mechanism of partial classes). In this automatically generated code, all controls on the page are defined as protected variables so that they can be accessed in the code.
  4. The compiler ASP.NET creates another class to represent the .aspx page itself. This class inherits from your special separated code class (along with the additional code added to it). Name for this class ASP.NET creates it simply by adding the separated aspx suffix code to the class name (for example, WebForm1aspx). This class contains the code required for initializing the page and all its controls, as well as the final version of the rendered HTML markup. In addition, an instance of this particular class ASP.NET it will be created when requests to the page are received.

Linking events to event handlers

Most of the page code ASP.NET placed inside event handlers that respond to events in web controls. You can use Visual Studio to add an event handler to your code in one of three ways::

  • Enter it manually. In this case, the method is added directly to the page class. You must specify the appropriate parameters so that the signature of the event handler exactly matches the signature of the event that you are going to process. You will also need to edit the control handle so that it binds the control to the corresponding event handler by adding the EvEnt_op_name attribute.
  • Double-click on the control in the visual designer view. In this case, Visual Studio will create a default event handler for this control (and configure the control handle accordingly). For example, double-clicking on a page creates a Page event handler.Load, and a double click on the button is a handler for the Click event.
  • Select an event in the Properties window. Select the control and click the lightning bolt button in the Properties window. You will see a list of all events provided by this control. Double-click the field next to the event you want to process, and Visual Studio will automatically generate an event handler in the page class and configure the control handle.:

The second and third methods are most convenient. On the other hand, the third method is the most flexible, since it allows you to select a previously created method in the page class. Just select an event in the Properties window and click the drop-down arrow on the right. You will see a list of class methods that match the signature expected by this event. Then, in the list, you can select a method for connecting it, as shown in the figure above.

Visual Studio uses automatic event chaining, as shown by the Page directive. Automatic generation of event chains is based on two basic principles:

  • All page event handlers are enabled automatically based on the name of the event handler. In other words, the Page_Load() method is automatically called during page loading.
  • All event handlers of the control are enabled using attributes in the control handle. The attribute has the same name as the event, but is prefixed with On.

For example, if you are going to handle the Click event of a Button control, all you need to do is set the OnClick attribute in the handle of the control with the name of the event handler that you are going to use.

Of course, if you are familiar with events .If you are using .NET, then you know that there is another way to connect the event handler. This can be done dynamically in the code using delegates. Below is an example:

Button1.Click += Button1_Click;

This approach is used to create controls on the fly.

Leave a Reply

Your email address will not be published.

You May Also Like
Read More

Components .NET

A well-designed web application written for ASP.NET, will include separate components that can be organized as separate data…
Read More

App Model ASP.NET

Difference between applications ASP.NET and feature-rich client applications, which makes a lot of sense when analyzing the execution…