ASP.NET - Directives - Import
In ASP.NET, the "import" directive is used to reference namespaces that contain the classes used in the code-behind file of a web page.
The syntax of the "import" directive is as follows:
<%@ Import Namespace="NamespaceName" %>
Here, "NamespaceName" refers to the name of the namespace that contains the classes to be used in the code-behind file.
For example, if you want to use the System.Data.SqlClient namespace in the code-behind file, you can add the following import directive at the top of the file:
<%@ Import Namespace="System.Data.SqlClient" %>
After adding the import directive, you can use the classes and types from the imported namespace in the code-behind file without having to fully qualify the namespace each time.
Using the System namespace:
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
int result = Math.Max(5, 10);
Response.Write(result.ToString());
}
</script>
In this example, the System namespace is imported to use the Math class to find the maximum of two numbers.
Using the System.Collections.Generic namespace:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
List<string> names = new List<string>();
names.Add("John");
names.Add("Mary");
names.Add("Bob");
foreach (string name in names)
{
Response.Write(name + "<br>");
}
}
</script>
In this example, the System.Collections.Generic namespace is imported to use the List class to create a collection of strings.
Using the System.Linq namespace:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Linq" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (int number in evenNumbers)
{
Response.Write(number.ToString() + "<br>");
}
}
</script>
In this example, the System.Linq namespace is imported to use the Where extension method to filter even numbers from an array of integers.
These are just a few examples of how the import directive can be used to simplify the code-behind file in ASP.NET.