WebPages Classes

ASP.NET WebPages allows you to create and use custom classes to encapsulate logic, manage data, and improve code reusability. Classes help you follow object-oriented programming principles and keep your application organized.

Key Topics

Creating Custom Classes

Example

namespace MyApplication
{
    public class User
    {
        public string Name { get; set; }
        public string Email { get; set; }

        public string GetDetails()
        {
            return $"Name: {Name}, Email: {Email}";
        }
    }
}

Explanation: This example defines a simple User class with properties for Name and Email and a method to return user details.

Using Classes in WebPages

Example

@{
    var user = new MyApplication.User
    {
        Name = "John Doe",
        Email = "john@example.com"
    };
}

<p>@user.GetDetails()</p>

Explanation: This example demonstrates how to instantiate and use the User class within a Razor page to display user details dynamically.

Reusability with Classes

Example

namespace MyApplication
{
    public class MathHelper
    {
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
}

@{
    var result = MyApplication.MathHelper.Add(5, 10);
}

<p>The sum is: @result</p>

Explanation: This example shows how to create a reusable MathHelper class with a static method, allowing you to perform mathematical operations throughout your application.

Key Takeaways

  • Custom classes encapsulate logic and improve code maintainability.
  • Classes can be used to define reusable components and methods.
  • Object-oriented principles help organize large applications effectively.