Model Classes in Asp.net Core

Model Classes in Asp.net Core
Model classes are the foundation for representing the data your application works with. They typically mirror the structure of your data, whether it comes from a database, an API, or other sources.
Purpose:
Structure: Provide a well-defined structure for your data, including properties that correspond to the fields or attributes of your data entities.
Validation: Enforce data validation rules using attributes like [Required], [StringLength], and [Range].
Organization: Keep your application’s data logic organized and maintainable.
Example Model Class:
// Book.cs (Model)
namespace IActionResultExample.Models
{
    public class Book
    {
        public int? BookId { get; set; }
        public string? Author { get; set; }
 
        public override string ToString() // For easy display in this example
        {
            return $”Book object – Book id: {BookId}, Author: {Author}”;
        }
    }
}
 
Model Binding with Model Classes
Model binding with model classes simplifies the process of populating your model objects with data from incoming HTTP requests. Instead of manually extracting values from query strings, route data, or form data, you can directly use the model class as a parameter in your action method.
 
How it Works:
Action Parameter: Declare an action method parameter of your model class type.
Model Binding: The model binder automatically maps incoming request data to the properties of your model class based on their names.
Attribute Usage: You can use attributes like [FromQuery], [FromRoute], and [FromBody] to specify where the model binder should look for the data for each property.
 
Code
// HomeController.cs
[Route(“bookstore/{bookid?}/{isloggedin?}”)]
//Url: /bookstore/1/false?bookid=20&isloggedin=true&author=harsha
public IActionResult Index([FromQuery] int? bookid, [FromRoute] bool? isloggedin, Book book)
{
    // … validation and response logic …
    return Content($”Book id: {bookid}, Book: {book}”, “text/plain”);
}
In this code:
Model Class Parameter: The action method Index has a parameter named book.
[FromQuery] Attribute: The BookId property of the Book class has the [FromQuery] attribute, indicating that its value should be retrieved from the query string.
Automatic Binding: When a request like /bookstore/1/false?bookid=20&isloggedin=true&author=harsha comes in:
bookid (int?) will be 20 (from the query string, due to [FromQuery]).
isloggedin (bool?) will be true (from the route data, due to [FromRoute]).
book.Author (string?) will be “harsha” (from the query string, because no attribute was specified for the Author property so it defaults to looking in the query string).

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply