2.1.1. Understanding Models
Definition and Role of Models
What are models in MVC?
How models represent the data and business logic.
Creating Simple Models
Defining model classes in the Models folder.
Naming conventions for models.
2.1.2. Properties and Data Types
Common Data Types
String, int, decimal, DateTime, bool.
Nullable Types
Using nullable types for optional properties.
Auto-Implemented Properties
Simplifying property definitions.
2.1.3. Data Annotations and Validation
Using Data Annotations
[Required], [StringLength], [Range], [RegularExpression].
[Display] attribute for customizing labels and formats.
Implementing Validation Logic
Server-side validation using data annotations.
Custom validation attributes.
Error Messages and Localization
Customizing validation error messages.
Localizing error messages for different cultures.
2.1.4. Model Binding
How Model Binding Works
Binding form inputs to model properties.
Binding Complex Types
Handling nested objects and collections.
Custom Model Binders
Creating custom binders for special cases.
2.1.5. View Models
Understanding View Models
Separating domain models from presentation models.
Creating View Models
Defining view-specific properties.
Mapping Between Models and View Models
Manual mapping.
Using tools like AutoMapper.
2.1.6. Data Transfer Objects (DTOs)
Purpose of DTOs
Transferring data between layers.
Implementing DTOs
Creating DTO classes.
Mapping data to and from DTOs.
2.1.7. Business Logic in Models
Encapsulating Business Rules
Adding methods and properties that enforce business rules.
Fat Models vs. Anemic Models
Understanding where to place business logic.
Hands-On Exercises
Exercise 1: Create a Product model with properties like Id, Name, Description, Price, CategoryId.
Exercise 2: Apply data annotations to validate the Product model (e.g., [Required], [Range]).
Exercise 3: Implement a custom validation attribute to ensure the Price is a positive value.
Exercise 4: Create a ProductViewModel that includes additional properties like CategoryName for display purposes.
2.2. Views
2.2.1. Introduction to Razor View Engine
What is Razor?
Combining C# code with HTML.
Razor Syntax Basics
Razor code blocks (@{ }), expressions (@), comments (@* *@).
Using C# in Views
Variables, loops (@for, @foreach), conditionals (@if, @else).
2.2.2. Creating and Rendering Views
View Naming Conventions
Matching view names with action methods.
Returning Views from Controllers
Using return View(); and return View("ViewName");.
Passing Data to Views
ViewData (ViewData["Key"]).
ViewBag (ViewBag.PropertyName).
Strongly-typed models (@model directive).
2.2.3. Layouts and Sections
Creating a Layout Page
Defining _Layout.cshtml.
Using Layouts in Views
Setting the layout in views (Layout = "_Layout";).
Defining Sections
Creating sections in views (@section Scripts { }).
Rendering Sections
Using @RenderSection in the layout.
Assistant
2.2.4. Partial Views
Purpose of Partial Views
Reusing common UI components (e.g., headers, footers).
Creating Partial Views
Naming convention (start with _).
Rendering Partial Views
Using @Html.Partial("_PartialViewName").
Passing Data to Partial Views
Passing models or using ViewData.
2.2.5. Display and Editor Templates
Creating Display Templates
Customizing how data types are displayed.
Creating Editor Templates
Customizing how input fields are rendered.
Using Templates in Views
@Html.DisplayFor and @Html.EditorFor.
2.2.6. Strongly-Typed Views
Advantages of Strongly-Typed Views
IntelliSense support.
Compile-time checking.
Specifying the Model Type
Using @model at the top of the view.
Accessing Model Properties
Using @Model.PropertyName.
2.2.7. HTML Helpers and Tag Helpers
HTML Helpers
Generating form elements (Html.TextBoxFor, Html.LabelFor).
Tag Helpers
Simplifying HTML with Tag Helpers (, ).
Custom Tag Helpers
Creating reusable components.
2.2.8. Bundling and Minification
Optimizing Static Files
Combining and minifying CSS and JS files.
Using LibMan (Library Manager)
Managing client-side libraries.
Hands-On Exercises
Exercise 1: Create a strongly-typed view to display a list of products.
Exercise 2: Implement a layout page with a header and footer.
Exercise 3: Create partial views for navigation menu and sidebar.
Exercise 4: Use display templates to format product prices.
2.3. Controllers
2.3.1. Understanding Controllers
Role of Controllers
Handling user input and responses.
Creating Controllers
Inheriting from Controller.
Naming Conventions
Controller names end with "Controller".
2.3.2. Action Methods
Defining Action Methods
Public methods that return IActionResult.
Returning Different Results
ViewResult, RedirectToActionResult, JsonResult, ContentResult, FileResult.
Asynchronous Actions
Using async and await.
2.3.3. Parameter Binding
From Query Strings
Automatically binding query parameters.
From Route Data
Binding parameters from URL segments.
From Form Data
Binding form inputs to action parameters.
2.3.4. Redirecting and Passing Data
Redirecting to Other Actions
RedirectToAction, RedirectToRoute.
TempData
Storing data between requests.
2.3.5. Controller Context
Accessing HttpContext
Request and response objects.
Using User.Identity
Accessing user information.
2.3.6. Filters and Action Attributes
Action Filters
Executing code before or after action methods.
Result Filters
Modifying the result before it's sent to the view.
Exception Filters
Handling exceptions globally.
Authorization Filters
Controlling access to actions.
2.3.7. Route Constraints in Controllers
Using Route Attributes
[Route("products/{id:int}")].
HTTP Verb Attributes
[HttpGet], [HttpPost], [HttpPut], [HttpDelete].
Hands-On Exercises
Exercise 1: Create a ProductController with actions for listing, creating, editing, and deleting products.
Exercise 2: Use parameter binding to retrieve product IDs from the URL.
Exercise 3: Implement action filters to log the execution of action methods.
2.4. Hands-On Project for Module 2
Project: Build a basic product management system.
Create models for Product and Category.
Implement views and controllers for CRUD operations.
Use layouts, partial views, and templates for the UI.
Apply validation and data annotations.
Utilize filters for logging and authorization.
from this module outline, please explain and write in detail about 2.1.3 and 2.1.4
Module 2: Deep Dive into MVC Components
2.1.3 Data Annotations and Validation
Data Annotations provide a way to enforce validation rules and configure metadata for your models in ASP.NET MVC applications. They are attributes that you apply directly to your model properties to specify validation logic and display behaviors. This section covers how to use data annotations effectively, implement both built-in and custom validation logic, and handle error messages with localization.
Using Data Annotations
1. Common Data Annotations:
[Required]: Ensures that a property must have a value. It's used to enforce mandatory fields.
csharp
public class Product
{
[Required(ErrorMessage = "Product name is required.")]
public string Name { get; set; }
}
[StringLength]: Specifies the minimum and maximum length of a string property.
csharp
public class Product
{
[StringLength(100, MinimumLength = 10, ErrorMessage = "Description must be between 10 and 100 characters.")]
public string Description { get; set; }
}
[Range]: Restricts a numeric property to a specified range.
csharp
public class Product
{
[Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
public decimal Price { get; set; }
}
[RegularExpression]: Validates a property against a specified regular expression pattern.
csharp
public class Product
{
[RegularExpression(@"^[A-Z]{3}-\d{3}$", ErrorMessage = "Code must follow the pattern AAA-123.")]
public string Code { get; set; }
}
2. [Display] Attribute:
The [Display] attribute is used to customize the display name, description, and format of a property in the UI.
Name: Changes the label displayed for the property.
csharp
public class Product
{
[Display(Name = "Product Name")]
public string Name { get; set; }
}
Description: Provides a detailed description, often used in tooltips.
csharp
public class Product
{
[Display(Description = "Enter the product's complete name.")]
public string Name { get; set; }
}
Format: Specifies the display format for the property, particularly useful for dates and numbers.
csharp
public class Product
{
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Price { get; set; }
}
Implementing Validation Logic
1. Server-Side Validation Using Data Annotations:
Data annotations automatically integrate with ASP.NET MVC's model binding and validation framework, enabling server-side validation without additional code.
Example:
csharp
public class Product
{
[Required]
public string Name { get; set; }
[Range(0.01, 1000.00)]
public decimal Price { get; set; }
}
public class ProductController : Controller
{
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save the product to the database
return RedirectToAction("Index");
}
// If validation fails, return the view with validation messages
return View(product);
}
}
Explanation:
When the form is submitted, MVC automatically checks the Product model against the data annotations.
If ModelState.IsValid returns false, the view is returned with validation error messages displayed.
2. Custom Validation Attributes:
Sometimes, built-in data annotations are insufficient for specific validation requirements. In such cases, you can create custom validation attributes by inheriting from ValidationAttribute.
Creating a Custom Validation Attribute:
csharp
public class PositivePriceAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null && value is decimal price)
{
if (price > 0)
{
return ValidationResult.Success;
}
}
return new ValidationResult("Price must be a positive value.");
}
}
Applying the Custom Attribute:
csharp
public class Product
{
[PositivePrice]
public decimal Price { get; set; }
}
Explanation:
PositivePriceAttribute ensures that the Price property is a positive decimal.
If the validation fails, a custom error message is returned.
Error Messages and Localization
1. Customizing Validation Error Messages:
You can customize error messages directly in the data annotations or define them in resource files for better management and localization.
Inline Error Messages:
csharp
public class Product
{
[Required(ErrorMessage = "Product name is required.")]
public string Name { get; set; }
}
Using Resource Files for Error Messages:
Step 1: Create a resource file (e.g., ValidationMessages.resx) and add key-value pairs for error messages.
Step 2: Reference the resource in your data annotations.
csharp
public class Product
{
[Required(ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "NameRequired")]
public string Name { get; set; }
}
Resources Example (ValidationMessages.resx):
Name
Value
NameRequired
Product name is required.
PriceRange
Price must be between 1 and 1000.
2. Localizing Error Messages for Different Cultures:
To support multiple languages, create separate resource files for each culture (e.g., ValidationMessages.en.resx, ValidationMessages.es.resx) and configure your application to select the appropriate resource based on the user's culture.
Example:
csharp
public class Product
{
[Required(ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "NameRequired")]
public string Name { get; set; }
}
ValidationMessages.en.resx:
Name
Value
NameRequired
Product name is required.
ValidationMessages.es.resx:
Name
Value
NameRequired
El nombre del producto es obligatorio.
Configuring Localization in Startup.cs:
csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllersWithViews()
.AddDataAnnotationsLocalization();
// Other configurations
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var supportedCultures = new[] { "en", "es" };
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
// Other middleware
}
Explanation:
The application now supports English and Spanish cultures.
Based on the user's browser settings or explicit selection, the appropriate resource file is used for error messages.
2.1.4 Model Binding
Model Binding is the process in ASP.NET MVC that maps HTTP request data (like form fields, query strings, and route data) to action method parameters or model properties. It simplifies the process of working with user input by automatically converting and validating the data.
How Model Binding Works
1. Binding Form Inputs to Model Properties:
When a form is submitted, MVC's model binder matches form field names with model property names to populate the model.
Example:
csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductController : Controller
{
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save product and redirect
}
return View(product);
}
}
The form fields Name and Price are posted to the Create action.
MVC binds these values to the Product model's properties based on matching names.
2. Handling Different Data Sources:
Model binding can handle various data sources, including form data, query strings, and route data.
Combining Data Sources:
If an action method has parameters from different data sources, model binding handles each appropriately.
csharp
public IActionResult Search(string query, int page)
{
// 'query' from query string or form data
// 'page' from query string or route data
}
Binding Complex Types
1. Handling Nested Objects:
Model binding can map complex types, including nested objects, by using dot notation in form field names.
Example:
csharp
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public Category Category { get; set; }
}
public class ProductController : Controller
{
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save product with category
}
return View(product);
}
}
The Category property within Product is a nested object.
The form inputs Category.CategoryName map to the nested Category object within the Product model.
2. Binding Collections:
Model binding can handle collections (e.g., lists, arrays) by using indexed naming in form fields.
Example:
csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public List<Tag> Tags { get; set; }
}
public class Tag
{
public int TagId { get; set; }
public string TagName { get; set; }
}
public class ProductController : Controller
{
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save product with tags
}
return View(product);
}
}
The Tags property is a collection within the Product model.
Using a loop with indexed naming (Tags[0].TagName, Tags[1].TagName, etc.) allows model binding to map the inputs to the collection elements.
Custom Model Binders
While the default model binder handles most scenarios, there are cases where you need more control over the binding process. Custom model binders allow you to define how specific types or parameters are bound.
1. Creating a Custom Model Binder:
Scenario:
Suppose you have a model property that requires special parsing or transformation during binding.
Example: Parsing a Comma-Separated String into a List:
csharp
public class Registration
{
public string Username { get; set; }
[CommaSeparatedList]
public List<string> Roles { get; set; }
}
public class CommaSeparatedListAttribute : ModelBinderAttribute
{
public CommaSeparatedListAttribute() : base(typeof(CommaSeparatedListBinder))
{
}
}
public class CommaSeparatedListBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(value))
{
bindingContext.Result = ModelBindingResult.Success(new List<string>());
return Task.CompletedTask;
}
var result = value.Split(',').Select(r => r.Trim()).ToList();
bindingContext.Result = ModelBindingResult.Success(result);
return Task.CompletedTask;
}
}
Applying the Custom Model Binder:
csharp
2. Registering Custom Model Binders Globally:
If you need to apply a custom model binder to all instances of a specific type, register it in Startup.cs.
Example:
csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(options =>
{
options.ModelBinderProviders.Insert(0, new CommaSeparatedListBinderProvider());
});
}
public class CommaSeparatedListBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(List<string>))
{
return new CommaSeparatedListBinder();
}
return null;
}
}
Explanation:
CommaSeparatedListBinderProvider checks if the model type is List<string> and provides the CommaSeparatedListBinder.
Inserting the provider at position 0 ensures it takes precedence over default binders.
Hands-On Exercises Related to 2.1.3 and 2.1.4
To reinforce the concepts covered in sections 2.1.3 and 2.1.4, here are some practical exercises:
Exercise 2: Apply Data Annotations to Validate the Product Model
Objective:
Enhance the Product model by applying appropriate data annotations to enforce validation rules.
Steps:
Define the Product Model:
csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int CategoryId { get; set; }
}
Apply Data Annotations:
csharp
public class Product
{
public int Id { get; set; }
[Required(ErrorMessage = "Product name is required.")]
[StringLength(50, ErrorMessage = "Name cannot exceed 50 characters.")]
public string Name { get; set; }
[StringLength(200, ErrorMessage = "Description cannot exceed 200 characters.")]
public string Description { get; set; }
[Range(0.01, 10000.00, ErrorMessage = "Price must be between $0.01 and $10,000.")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Category is required.")]
public int CategoryId { get; set; }
}
The Create view will display validation errors based on the data annotations applied to the Product model.
Users will receive immediate feedback on form submission if any validation rules are violated.
Exercise 3: Implement a Custom Validation Attribute to Ensure the Price is a Positive Value
Objective:
Create and apply a custom validation attribute to enforce that the Price property of the Product model is a positive value.
Steps:
Create the Custom Validation Attribute:
csharp
public class PositivePriceAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null && decimal.TryParse(value.ToString(), out decimal price))
{
if (price > 0)
{
return ValidationResult.Success;
}
}
return new ValidationResult("Price must be a positive value.");
}
}
Apply the Custom Attribute to the Price Property:
csharp
public class Product
{
public int Id { get; set; }
[Required(ErrorMessage = "Product name is required.")]
[StringLength(50, ErrorMessage = "Name cannot exceed 50 characters.")]
public string Name { get; set; }
[StringLength(200, ErrorMessage = "Description cannot exceed 200 characters.")]
public string Description { get; set; }
[Required(ErrorMessage = "Price is required.")]
[PositivePrice]
public decimal Price { get; set; }
[Required(ErrorMessage = "Category is required.")]
public int CategoryId { get; set; }
}
Try submitting the form with a negative price value (e.g., ).
Outcome:
The PositivePriceAttribute ensures that users can only submit products with a positive price.
Custom validation provides more specific and meaningful error messages tailored to business rules.
Exercise 4: Create a ProductViewModel that Includes Additional Properties Like CategoryName for Display Purposes
Objective:
Implement a ViewModel to present product data along with related category information, separating domain models from presentation concerns.
Steps:
Define the ProductViewModel:
csharp
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int CategoryId { get; set; }
public string CategoryName { get; set; } // Additional property for display
}
Modify the Controller to Use the ViewModel:
csharp
public class ProductController : Controller
{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public IActionResult Index()
{
var products = _context.Products.Include(p => p.Category).ToList();
var productViewModels = products.Select(p => new ProductViewModel
{
Id = p.Id,
Name = p.Name,
Description = p.Description,
Price = p.Price,
CategoryId = p.CategoryId,
CategoryName = p.Category.CategoryName
}).ToList();
return View(productViewModels);
}
}
Create or Update the Index View to Use the ViewModel:
html
Outcome:
Utilizing a ViewModel enhances flexibility in presenting data tailored to the view's requirements.
It promotes better maintainability and scalability by decoupling domain models from view-specific data.
Summary
In sections 2.1.3 and 2.1.4, we've explored the powerful features of Data Annotations for validating model data and customizing display metadata. Implementing both built-in and custom validation ensures that your application enforces business rules effectively. Model Binding further streamlines data handling by automatically mapping user input to model properties, even for complex types and collections. By mastering these concepts, you can build robust and user-friendly MVC applications that maintain data integrity and provide meaningful feedback to users.
By leveraging these resources, you can deepen your understanding and stay updated with best practices in ASP.NET MVC development.
Not yet included in a published release.
public class RegistrationController : Controller
{
[HttpPost]
public IActionResult Register(Registration registration)
{
if (ModelState.IsValid)
{
// Process registration
}
return View(registration);
}
}
The Roles property is a List<string> and is expected to receive a comma-separated string from the form.
CommaSeparatedListBinder parses the input string and populates the Roles list accordingly.
The [CommaSeparatedList] attribute applies the custom binder to the Roles property.
Controller Action:
csharp
public class ProductController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save to database
return RedirectToAction("Index");
}
return View(product);
}
}
-10
The form should display the error message: "Price must be a positive value."
Separation of Concerns: The ProductViewModel separates the data needed for display (CategoryName) from the domain model (Product), which only contains the CategoryId.
Mapping Data:
The controller retrieves products and their associated categories from the database.
It then maps each Product to a ProductViewModel, including the CategoryName for display purposes.
View Usage: The view strongly types to IEnumerable<ProductViewModel> and displays the CategoryName alongside product details.