Unit-4 (Model, Model Building and Validations & URL Routing )
Unit-4 (Model, Model Building and Validations & URL Routing )
Model
Model Binding
Model Validation
URL Routing
Attributes of URL Routing
By Bijaya Tamang
ROLL NO:5
Model
The model is a collection of objects, which hold the data of our application and it may
contain the associated business logic. The model classes represent domain-specific data and
business logic in the MVC application and are simply c # classes. especially in the context of
MVC (Model-View-Controller) architecture, a model represents the data and the business
logic of an application. It serves as the central part of the application, holding the data
structure and interacting with the database or other data sources. The model is divided into
several categories based on how and where they are used. The three distinctions are as
follow:
A. Domain Model
A Domain Model represents the core business logic and data of the application. It defines
the real-world entities, their attributes, and relationships within the context of the
application's domain.
Example:
using System;
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
}
class Program
{
static void Main()
{
var product = new Product { Id = 1, Name = "Laptop", Price = 1500, Stock =
10 };
Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price:
{product.Price}, Stock: {product.Stock}");
}
}
OUTPUT:
B. View Model
Purpose: Tailored for the view layer to provide only the necessary data.
Example Usage: Used for passing data from controllers to views or for validation.
Characteristics:
o Does not map directly to database tables.
o Includes data annotations for validation and display metadata.
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
class Program
ValidateProduct(product);
{
foreach (var error in results)
{
else
Console.WriteLine("Product is valid!");
OUTPUT:
Example:
using System;
class Program
}
OUTPUT:
Summary
Each model type serves a specific purpose to maintain separation of concerns and improve
code clarity and maintainability in .NET applications.
Model Binding
Model Binding is a feature in frameworks like ASP.NET MVC or Razor Pages that
simplifies mapping incoming request data (e.g., form fields, query strings, route data) to
model objects. The model binding extracts the data from an HTTPS request and provide them
to the controller action method parameters. The action method parameters may be simple
types like integers, strings etc. or complex type such as students, order, product etc.
1. Request Data Source: Model binding reads data from sources such as query strings, form
fields, or JSON payloads.
2. Parameter Matching: It matches the request data to parameters in the controller action
method or properties in a model based on names.
3. Type Conversion: Automatically converts the data to the appropriate data type (e.g., string
to int or Date Time).
4. Validation: Optionally validates the bound data using data annotations or custom validation
logic.
For example:
Benefits:
Model binding in ASP.NET Core simplifies the process of mapping HTTP request data to
action method parameters or properties of model objects. While it can handle simple types
like int, string, or bool, it also supports complex/user-defined types like classes and nested
objects.
Complex/User-Defined Types in Model Binding:
A complex type is typically a class or struct containing multiple properties, each of which
may also be simple or complex types. Model binding for these types automatically maps the
request data to the corresponding properties.
ASP.NET Core binds complex types by recursively matching property names from the
request data to the properties in the class. The data source can be form fields, query strings,
route data, or JSON payloads.
[HttpPost]
public IActionResult Create(User user)
{
if (ModelState.IsValid)
{
// Model binding populates the 'User' object, including the nested 'Address'.
// Process the user object.
return Ok(user);
}
return BadRequest(ModelState);
}
1. Form Data:
2. Name=John&Address.Street=Main+St&Address.City=Metropolis&Address.ZipCode
=12345
3. JSON Payload (for APIs):
4. {
5. "Name": "John",
6. "Address": {
7. "Street": "Main St",
8. "City": "Metropolis",
9. "ZipCode": "12345"
10. }
11. }
Sometimes, the default model binding mechanism doesn't meet specific requirements (e.g., a
custom format, unconventional data source). In such cases, you can create a custom model
binder.
Suppose you need to bind a user object where all data comes as a single JSON string in the
query.
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Text.Json;
using System.Threading.Tasks;
try
{
var user = JsonSerializer.Deserialize<User>(json);
bindingContext.Result = ModelBindingResult.Success(user);
}
catch
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"Invalid JSON format.");
}
return Task.CompletedTask;
}
}
Step 2: Apply the Binder Use the ModelBinder attribute to specify the custom binder.
[ModelBinder(BinderType = typeof(UserModelBinder))]
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
Controller Example:
[HttpPost]
public IActionResult Create([ModelBinder] User user)
{
if (ModelState.IsValid)
{
// Custom binder has populated the 'User' object.
return Ok(user);
}
return BadRequest(ModelState);
}
Request Example:
POST /api/users?user={"Id":1,"Name":"John","Address":{"Street":"Main
St","City":"Metropolis","ZipCode":"12345"}}
3. Validation:
o ASP.NET Core validates complex types using data annotations like
[Required], [Range], etc., applied to properties in both simple and complex
models.
Conclusion
Model binding in ASP.NET Core is powerful and flexible, handling complex and user-
defined types seamlessly. For more specialized scenarios, custom model binders provide a
way to extend this capability to meet unique application requirements.
Model Validation
Model Validation in ASP.NET Core ensures that the data received from the user conforms
to the application's business rules and constraints. Validation helps prevent invalid or
incomplete data from entering the system, thereby enhancing application reliability and
security.
1. Validation Rules:
o Validation rules are defined using attributes applied to model properties.
o These attributes come from the System.ComponentModel.DataAnnotations
namespace.
3. Validation Results:
o The ModelState object indicates whether the model is valid.
o The application can respond to invalid data by displaying error messages or
returning appropriate HTTP status codes.
Here are the most commonly used validation attributes in ASP.NET Core:
1. [Required]
Example:
{
[Required(ErrorMessage = "Product name is required.")]
public string Name { get; set; }
}
2. [String Length]
Example:
3. [Range]
Example:
4. [RegularExpression]
Example:
5. [EmailAddress]
Example:
6. [Compare]
Compares two properties for equality.
Example:
7. [CreditCard]
Example:
8. [Phone]
Example:
9. [Url]
Example:
Usage:
Validation in Controllers
During an HTTP request, the framework validates the model and updates the ModelState.
You can check ModelState.IsValid in your controller actions.
Example in a Controller
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Process the valid product.
return RedirectToAction("Index");
}
return View(product); // Return validation errors to the view.
}
Validation in APIs
In Web APIs, ASP.NET Core automatically responds with a 400 Bad Request status if the
model is invalid.
Example
[HttpPost]
public IActionResult Create([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Returns validation errors in the response.
}
return Ok(product);
}
Client-Side Validation
In Razor Pages or MVC Views, validation attributes also work on the client side when using
libraries like jQuery Validation.
<form asp-action="Create">
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
<button type="submit">Submit</button>
</form>
Summary
Model Validation ensures that data meets application rules and constraints.
Built-in Validation Attributes like [Required], [Range], and [EmailAddress] make it easy to
enforce common rules.
Custom Validation can handle more complex scenarios.
Client-Side Validation enhances user experience by providing immediate feedback.
Validation results are accessible via the ModelState object and can influence how requests are
processed in controllers or APIs.
1. Request Matching:
o The routing system matches the incoming HTTP request (path and method) against
predefined routes.
o A successful match determines which controller and action to invoke.
2. Route Templates:
o Developers define route templates, which can include static segments and
placeholders for dynamic data.
3. Routing Middleware:
o Routing in ASP.NET Core is handled by middleware that processes the request and
determines the appropriate action.
Key Features of URL Routing
1. Route Templates
Routes are defined using templates that include static paths and placeholders.
Placeholders are enclosed in curly braces ({}) and represent dynamic values.
Example:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
2. Attribute Routing
Example:
[Route("products/{id?}")]
public IActionResult Details(int? id)
{
// Action logic
}
3. Parameters in Routes
4. Constraints
Constraints restrict the values that parameters can accept.
Applied using route constraints like int, string, or custom validators.
Example:
[Route("products/{id:int}")]
public IActionResult Details(int id)
{
// Only matches if 'id' is an integer
}
Common Constraints:
Constrain Description
t
int Matches integer values
guid Matches GUIDs
minlength Minimum string length
maxlength Maximum string length
regex Matches a regular expression
5. Endpoint Routing
Example:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
6. Route Priorities
7. Route Values
Route values are extracted from the URL and passed to the action method as
parameters.
Example: For the route /products/details/5, the route template {controller}/{action}/{id} produces:
controller = "products"
action = "details"
id = 5
8. Generating URLs
URLs can be dynamically generated using routing helpers like Url.Action or Url.RouteUrl.
This ensures consistency and avoids hardcoding URLs.
Example:
1. User-Friendly URLs:
o Create clean and readable URLs (/products/details/5 vs /products?id=5).
2. SEO Optimization:
o Meaningful URLs improve search engine rankings.
3. Dynamic Behavior:
o Easily handle dynamic data and parameters in URLs.
4. Centralized Configuration:
o Manage all routes centrally or through attributes for flexibility.
Startup.cs:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "custom",
pattern: "products/{category}/{id?}",
defaults: new { controller = "Products", action = "Category" });
});
Controller:
public class ProductsController : Controller
{
public IActionResult Index()
{
return View();
}
URLs Handled:
/ → HomeController.Index
/products/electronics → ProductsController.Category(category: "electronics")
/products/electronics/5 → ProductsController.Category(category: "electronics", id: 5)
Summary
URL Routing in ASP.NET Core maps HTTP requests to specific actions or Razor
Pages.
Supports route templates, attribute routing, constraints, and default values.
Helps create user-friendly, SEO-optimized, and dynamic URLs.
Endpoint Routing centralizes route management in modern ASP.NET Core
applications.
Asked Questions:
1.What is the role of adapter class in ADO.NET? List some features of URL routing.