0% found this document useful (0 votes)
7 views

Unit-4 (Model, Model Building and Validations & URL Routing )

Uploaded by

kojing.t.tamang1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit-4 (Model, Model Building and Validations & URL Routing )

Uploaded by

kojing.t.tamang1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT 4

Titles Of the Presentations:

 Model
 Model Binding
 Model Validation
 URL Routing
 Attributes of URL Routing

By Bijaya Tamang

BSC CSIT 6TH SEM

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.

 Purpose: Encapsulates the business logic and rules.


 Example Usage: Used to interact with databases or perform core computations.
 Characteristics:
o Directly maps to database tables in ORM frameworks like Entity Framework.
o Contains minimal validation or none (validation is handled elsewhere, such as
View Models).

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

A View Model is designed specifically to represent data that is displayed in the UI


(View). It may combine data from multiple domain models or include additional fields
needed only for presentation purposes.

 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;

public class ProductViewModel

[Required(ErrorMessage = "Name is required.")]

[MinLength(3, ErrorMessage = "Name must be at least 3 characters long.")]


public string Name { get; set; }
[Required(ErrorMessage = "Price is required.")]

[Range(0.01, 10000, ErrorMessage = "Price must be between 0.01 and 10,000.")]

public decimal Price { get; set; }

[Range(1, int.MaxValue, ErrorMessage = "Stock must be at least 1.")]

public int Stock { get; set; }

class Program

static void Main()

var product = new ProductViewModel { Name = "L", Price = 0, Stock = 0 }; //


Test invalid product

ValidateProduct(product);

static void ValidateProduct(ProductViewModel product)

var context = new ValidationContext(product);

var results = new List<ValidationResult>();

if (!Validator.TryValidateObject(product, context, results, true))

{
foreach (var error in results)
{

Console.WriteLine($"Validation error: {error.ErrorMessage}");

else

Console.WriteLine("Product is valid!");

OUTPUT:

C. Data Transfer Object (DTO)

A DTO is used to transfer data between different layers of an application or between


applications (e.g., in API responses). Unlike domain models, DTOs are often simplified
representations of data and may omit unnecessary details.

 Purpose: Optimize data exchange by including only required fields.


 Example Usage: Used in APIs to send or receive data without exposing the entire
domain model.
 Characteristics:
o Does not include business logic.
o Focuses solely on data transport.

Example:

using System;

public class ProductDTO

public int Id { get; set; }

public string Name { get; set; }

public decimal Price { get; set; }

class Program

static void Main()

var product = new ProductDTO { Id = 1, Name = "Laptop", Price = 1500 };

Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price:


{product.Price}");

}
OUTPUT:

Comparison of Model Types:

Model Type Purpose Layer Used Contains Directly


Validation Maps to DB
Domain Represents core Business/Data Minimal or Yes
Model business data and logic Layer None
View Model Represents data for UI Presentation Yes No
presentation Layer
DTO Optimized for data Communication No No
exchange between Layer
systems

Summary

 Domain Models: Core business data and logic.


 View Models: Tailored for UI presentation and validation.
 DTOs: Streamlined for data exchange between systems or layers.

Each model type serves a specific purpose to maintain separation of concerns and improve
code clarity and maintainability in .NET applications.

 Key Features of a Model:

o Encapsulates application data (e.g., user data, product details).


o Implements business rules and logic.
o Interacts with the database for CRUD (Create, Read, Update, Delete)
operations.

For example, in C# ASP.NET:

public class User


{
public int Id {get; set;}
public string Name {get; set;}
public string Email {get; set;}
}

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.

How Model Binding Works

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:

public IActionResult Create (User user)


{
// The User object is automatically populated with data from the request.
// Save the user to the database or process it further.
return View(user);
}

Benefits:

 Reduces boilerplate code.


 Automatically validates and maps data.
 Simplifies handling of form submissions or API payloads.

Model Binding in ASP.NET Core with Complex and User-Defined Types

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.

Example: Complex Type Model

public class Address


{
public string Street { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
}

public class User


{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}

Handling Complex Types in ASP.NET Core

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.

Controller Action Example

[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);
}

Request Data Example

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. }

Custom Model Binding for User-Defined Types

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.

Custom Model Binder for User-Defined Type

Suppose you need to bind a user object where all data comes as a single JSON string in the
query.

Step 1: Create a Custom Binder

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Text.Json;
using System.Threading.Tasks;

public class UserModelBinder : IModelBinder


{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var json =
bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue;
if (string.IsNullOrEmpty(json))
{
return Task.CompletedTask;
}

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"}}

Key Points to Remember

1. Complex Type Binding:


o ASP.NET Core binds nested properties recursively.
o Use property names like Address.Street in form data or JSON for nesting.

2. Custom Model Binders:


o Implement the IModelBinder interface for advanced scenarios.
o Useful when the data source or format deviates from conventional patterns.

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.

4. Explicit Binding Attributes:


o Use [FromQuery], [FromBody], [FromForm], or [FromRoute] to specify data
sources explicitly.

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.

How Model Validation Works

1. Validation Rules:
o Validation rules are defined using attributes applied to model properties.
o These attributes come from the System.ComponentModel.DataAnnotations
namespace.

2. Validation During Model Binding:


o When ASP.NET Core binds HTTP request data to a model, it automatically
validates the model using the applied attributes.
o If validation fails, errors are added to the ModelState object.

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.

Common Validation Attributes

Here are the most commonly used validation attributes in ASP.NET Core:

1. [Required]

Specifies that a property must have a value.

Example:

public class Product

{
[Required(ErrorMessage = "Product name is required.")]
public string Name { get; set; }
}
2. [String Length]

Limits the length of a string property.

Example:

public class Product


{
[StringLength(100, ErrorMessage = "Name cannot exceed 100 characters.")]
public string Name { get; set; }
}

3. [Range]

Enforces a numeric range.

Example:

public class Product


{
[Range(0.01, 10000, ErrorMessage = "Price must be between 0.01 and 10,000.")]
public decimal Price { get; set; }
}

4. [RegularExpression]

Validates a property against a regular expression.

Example:

public class User


{
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Only letters are allowed.")]
public string Name { get; set; }
}

5. [EmailAddress]

Validates an email address format.

Example:

public class User


{
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
}

6. [Compare]
Compares two properties for equality.

Example:

public class User


{
public string Password { get; set; }

[Compare("Password", ErrorMessage = "Passwords do not match.")]


public string ConfirmPassword { get; set; }
}

7. [CreditCard]

Validates a credit card number format.

Example:

public class Payment


{

[CreditCard(ErrorMessage = "Invalid credit card number.")]


public string CardNumber { get; set; }
}

8. [Phone]

Validates a phone number format.

Example:

public class Contact


{
[Phone(ErrorMessage = "Invalid phone number.")]
public string PhoneNumber { get; set; }
}

9. [Url]

Validates a URL format.

Example:

public class Website


{
[Url(ErrorMessage = "Invalid URL.")]
public string WebsiteUrl { get; set; }
}

Custom Validation Attributes


If the built-in validation attributes don't meet your requirements, you can create custom
validation logic by extending the ValidationAttribute class.

Example: Custom Validation

public class CustomPriceAttribute : ValidationAttribute


{
protected override ValidationResult IsValid(object value, ValidationContext
validationContext)
{
if (value is decimal price && price < 0)
{
return new ValidationResult("Price cannot be negative.");
}
return ValidationResult.Success;
}
}

Usage:

public class Product


{
[CustomPrice]
public decimal Price { get; set; }
}

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.

 Use the @Html.ValidationMessageFor or @Html.ValidationSummary helpers to


display error messages in the view.

Example in Razor View

<form asp-action="Create">
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>

<input asp-for="Price" />


<span asp-validation-for="Price" 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.

URL Routing in ASP.NET Core


URL Routing in ASP.NET Core is a mechanism that maps incoming HTTP requests to
specific action methods in controllers or Razor Pages. It allows developers to define URL
patterns that dictate how requests are handled, making URLs user-friendly, meaningful, and
SEO-friendly.

How Routing Works in ASP.NET Core

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?}");
});

 {controller}: Maps to the controller name.


 {action}: Maps to the action method.
 {id?}: Optional parameter.

2. Attribute Routing

 Routing can be defined directly on controller actions using attributes.


 Provides greater flexibility and fine-grained control.

Example:

[Route("products/{id?}")]
public IActionResult Details(int? id)
{
// Action logic
}

3. Parameters in Routes

 Required Parameters: Must be provided in the URL.


o Example: /products/{id} requires id.
 Optional Parameters: Indicated by ? and may be omitted.
o Example: /products/{id?}.
 Default Values: Assign default values to parameters.
o Example: /products/{id=1} uses 1 if id is not provided.
 Catch-All Parameters: Capture all remaining segments.
o Example: /products/{*allSegments}.

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

 Introduced in ASP.NET Core 3.0.


 Centralized routing configuration in the middleware pipeline.
 Defined in Startup.cs within app.UseEndpoints.

Example:

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

6. Route Priorities

 Routes are evaluated in the order they are defined.


 The first matching route is executed.
 Specific routes should appear before generic ones.

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:

<a href="@Url.Action("Details", "Products", new { id = 5 })">Product Details</a>

Benefits of URL Routing

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.

Example: Complete Routing Configuration

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();
}

public IActionResult Category(string category, int? id)


{
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.

You might also like