In this article, we will understand the model binding and validation that will be carried out by 'record' types c#9 feature in MVC application.
Specs:
C#9
.Net5 MVC Application
C# 9 Record Types:
The Record Types has been introduced in C# 9 feature. Using Record Types, it is effortless to create immutable reference types. Most features supported by 'Class' will be supported by the 'Record' types but in the case to make them immutable(not allow changes in the object) then it will be an ideal choice to use 'Record' types.
Record Syntax Type1:
public record Profile { public string FirstName { get; } public string MiddleName { get; } }Above Record, the syntax looks similar to 'class' but only defense instead of 'class' we use 'record' keyword. Always declare properties as private in records that fulfill our immutable feature.
Record Syntax Type2:
public record Profile(string FirstName, string MiddleName)This syntax declaration almost looks like a method or constructor. The input parameters of the record will be created as init(init is an access specifier that makes properties assigned at constructor or first-time object initialization) properties implicitly.
Create An MVC Application:
To understand the implementation of 'record' types for model binding and validation we can create a sample application by selecting any one template like 'MVC', 'Razor Page', and 'Web API'. Here for this article, I'm using an MVC template. For development, we can choose any IDE, but the most preferred are Visual Studio 2019(Version 16.8.* that supports .Net5 applications) or Visual Studio Code.
Create A Sample Record:
Let's begin by creating a sample record type that will be used as a model object.
Models/ProfileModel.cs:
namespace Sample.MvcRecords.Models { public record Profile(string FirstName, string LastName, string Email); }Here created a 'Profile' record that contains 'FirstName', 'LastName', and 'Email' as init(init is an access specifier that makes properties assigned at constructor or first-time object initialization)
Get EndPoint With Record Type As ViewModel:
Here we are going to create a get endpoint whose ViewModel will be a record type.
Controllers/TestController.cs:
using Microsoft.AspNetCore.Mvc; using Sample.MvcRecords.Models; namespace Sample.MvcRecords.Controllers { [Route("test")] public class TestController : Controller { [Route("index")] [HttpGet] public IActionResult Index() { return View(); } } }
- Created as simple get endpoint that loads the simple form.
@model Profile <div> <form asp-action="profile-post"> <div class="form-group row"> <label asp-for="FirstName" class="col-sm-2 col-form-label">First Name</label> <div class="col-sm-10"> <input asp-for="FirstName" type="text" class="form-control" /> <span asp-validation-for="FirstName" class="text-danger"></span> </div> </div> <div class="form-group row"> <label asp-for="LastName" class="col-sm-2 col-form-label">Last Name</label> <div class="col-sm-10"> <input asp-for="LastName" type="text" class="form-control" /> <span asp-validation-for="LastName" class="text-danger"></span> </div> </div> <div class="form-group row"> <label asp-for="Email" class="col-sm-2 col-form-label">Email</label> <div class="col-sm-10"> <input asp-for="Email" type="text" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group row"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div>
- (Line: 1) The 'Profile' is a record type is used as ViewModel.
- The razor helper tags like 'asp-for', 'asp-validation-for' take ViewModel properties as values.
Use Record Type As Model Binding Value:
Now let's create a post endpoint to save the form values. For the post endpoint, the model binding value will be the record type.
Controllers/TestController.cs:
[Route("profile-post")] [HttpPost] public IActionResult Index(Profile profile) { if (ModelState.IsValid) { return Content("sucess"); } return View(profile); }
- (Line: 3) Here 'Profile' which is of type 'record' used as a model binder.
- In this sample post endpoint if the form data valid then it returns a simple string like 'success', else it returns form with error messages.
DataAnnotation In Record Types:
Similar to classes in 'record' also can add validation attributes of DataAnnotations on properties. So let's update our 'record' with validation attributes which will help to validate our sample form.
Models/ProfileModel.cs:
using System.ComponentModel.DataAnnotations; namespace Sample.MvcRecords.Models { public record Profile([Required]string FirstName, [Required]string LastName, [EmailAddress][Required]string Email); }
- Record fields were decorated with DataAnnotations validation attributes as similar as in classes.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on C#9 record types to use a ViewModel for model binding and for validation in MVC, Razor Page, and Web API applications. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment