Webpages Classes in ASP
Got it! Here’s a simple overview of using classes in ASP.NET Web Pages (the lightweight WebMatrix-style ASP.NET) — how to define and use your own classes in Web Pages (.cshtml or .vbhtml):
Using Classes in ASP.NET Web Pages
ASP.NET Web Pages lets you write server-side code directly in .cshtml or .vbhtml files, including defining classes to organize your code.
1. Define a Class in Razor (C#)
You can define classes inside @functions { ... } blocks in your .cshtml file:
@functions { public class Person { public string Name { get; set; } public int Age { get; set; } public string GetInfo() { return $"{Name} is {Age} years old."; } }}@{ var p = new Person { Name = "Alice", Age = 30 };}<p>@p.GetInfo()</p>2. Define a Class in VB Razor (.vbhtml)
Use @Functions ... End Functions block:
@Functions Public Class Person Public Property Name As String Public Property Age As Integer Public Function GetInfo() As String Return $"{Name} is {Age} years old." End Function End ClassEnd Functions@Code Dim p As New Person With {.Name = "Bob", .Age = 25}End Code<p>@p.GetInfo()</p>3. Organizing Classes in Separate Files
For larger projects, put classes in separate .cs or .vb files inside the App_Code folder — Web Pages automatically compiles these.
Example:
App_Code/Person.cs
public class Person{ public string Name { get; set; } public int Age { get; set; } public string GetInfo() { return $"{Name} is {Age} years old."; }}Then in your Razor page:
@{ var p = new Person { Name = "Charlie", Age = 28 };}<p>@p.GetInfo()</p>4. Using Namespaces
You can also define namespaces in your class files for better organization.
Summary
| Concept | Razor (C#) Syntax | Razor (VB) Syntax |
|---|---|---|
| Define class | @functions { class ... } | @Functions ... End Functions |
| Instantiate | var p = new Person(); | Dim p As New Person() |
| Separate files | Place .cs files in App_Code | Place .vb files in App_Code |
If you want examples on advanced class usage, inheritance, or integrating with Web Pages helpers, just ask!