Skip to main content

Asp.Net Core MVC Form Validation Techniques


Introduction:

Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library jQuery Validate.

In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples.

Getting Started:

Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio.

Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as below.
PersonController.cs:
using Microsoft.AspNetCore.Mvc;
namespace MvcValidation.App.Controllers
{
    [Route("person")]
    public class PersonController : Controller
    {
        [HttpGet]
        [Route("create")]
        public IActionResult Create()
        {
            return View();
        }
    }
}
Add MVC View name as 'Create.cshtml' which is furnished with a form to validate.
Views/Person/Create.cshtml:
@model Person

<div>
    <form asp-action="create-post">
        <div class="form-group row">
            <label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
            <div class="col-sm-10">
                <input asp-for="Name" type="text" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>

'Person' will be the model for the 'Create.cshtml' view. In the form, we can observer MVC Tag Helpers like 'asp-action', 'asp-for', 'asp-validation-for' will be discussed in much more details in later steps.

Now Add Model 'Person.cs' which binds or holds the form data.
Models/Person.cs:
using System.ComponentModel.DataAnnotations;
namespace MvcValidation.App.Models
{
    public class Person
    {
        public string Name { get; set; }
    }
}
Now Observer Html above, MVC Tag Helpers value assigned is "Name" which is from the 'PersonModel'. Similarly, we have to bind properties from model class with the Html to consume the validation benefits provided by Dotnet Core.

Now run the application and navigate to "https://localhost:44397/person/create"
Now open browser developers tools and observe the Html rendered inside form where we can see some 'data-{something}' attributes, id's, the name's are rendered. If you wondered how this happens, then the answer will be MVC Tag Helpers.

Configure Server-Side Validations:

Asp.Net Core MVC server-side validation done by Data Annotations in which the properties for the form need to configure validation, those properties will be decoration with validation Attribute. Here are some built-in validation attributes provided by Dotnet Core:
  • [Compare] - validates two properties of a model match.
  • [EmailAddress] - validates that the property has a valid email format.
  • [Phone] - validates that the property has a valid phone number format.
  • [Range] - validates that the property value fallen within the specified range values.
  • [RegularExpression] - validates that the property has satisfied the given regular expression.
  • [Required] - validate that the property has some value, can not be null or empty.
  • [StringLength] - validate that the property value length should not exceed the length specified.
  • [Remote]- validates the input on the client, by calling the action method on the server through AJAX.
These Attribute [AttributeName(ErrorMessage= "custom message")] might allow optional input parameters to override default functionality, for example, they allow us to input error message to override the default one.

Let's add [Required] attribute to 'Name' property in Person Model. Update the code as below
Models/Person.cs:
[Required]
public string Name { get; set; }
Now Test the sample application again and open browser developer tools then inspect the form element. We can observe after adding validation attribute, in the Html input field two more 'data-{something}' attributes are added like 'data-val' and 'data-val-required'.
Now add a new action method that receives the form posted data and validates the form data. Update the code as below
PersonController.cs:
[HttpPost]
[Route("create-post")]
public IActionResult Create(Person person)
{
 if (!ModelState.IsValid)
 {
  return View(person);
 }
 return Content("Success");
}
  • In this Post action method, model validation can be check by using 'ModelState' which depends on the form model (our example Person.cs is form model). 
  • If model valid we returning some success string (in the real-time application based on the application requirement redirected to success view ) if validation fails then pass the model to view 'Create.cshml'. Because we are passing the model object which is invalid passing to the 'create.cshml', now the error messages will be displayed.
Now run the application, navigate to "https://localhost:44397/person/create" and submit the form with empty fields, now page gets reloaded and posted the form to 'create-post' route action method since validation fails page gets rendered as below.
Now open browser developers tools, and observe form tag, in that observe span tag which displays an error message. If you recall on form load check the span tag value which is empty because on form get action method we are not passing any 'Person' model. But if you submit a form to post action method where we passing model to view then we are seeing an error message rendered by the server.
Remember in this approach validation done by the server, so on every submission entire form gets posted to a server and reloads the page. So for every invalid form submission application will participate in reloading page.

Client Validation Using jQuery Unobtrusive Validation:

jQuery Unobtrusive Validation is a front-end validation library developed Microsoft. Using client-side validation benefits the application by reducing its number of round-trips to the server. Validating page without reloading page also looks like much more user-friendly applications.

  • Most work of this jQuery Unobtrusive Validation depends on the Html data attributes (like 'data-{someAttribute}' ). 
  • jQuery Unobtrusive Validation parses the data- attribute and passes the logic to jQuery validation. 'data-value' attribute set true( means 'data-val = true') makes the field is ready or configured to get validated by jQuery Unobtrusive Validation. 
  • When the field is ready to validate, the field must also contain data- attribute rule means 'data-val-ruleName' and value for this attribute will be the error message for this validation. 
  • jQuery Unobtrusive Validation has been configured to deal with some default data- attribute rules (one example like data-val-required=" filed must be required").
  • The field can contain additional values while validating can be passed via data- attribute rule parameter(like 'data-val-rulename-parameter1='5'')
  • Note:- From the above points we conclude that data- attributes used by jQuery Unobtrusive Validation, either we have to write every attribute manually on Html or if we can recall this article MVC Tag Helpers like 'asp-for', 'asp-validation-for' are helping to generates data- attributes dynamically on rendering the page.
Now to consume jQuery Unobtrusive Validation, when we create Asp.Net Core MVC template Project it's automatically adding those files in '_ValidationScriptsPartial.cshtml'.
Views/Shared/_ValidationScriptsPartial.cshml:
Now load this partial script on to the 'Create.cshmtl' as below
Create.cshtml:
@section  Scripts{

@await Html.PartialAsync("/Views/Shared/_ValidationScriptsPartial.cshtml")
}
Now let's add data- attributes in the form manually, update the input field in the form as below
Create.cshtml:
<div class="col-sm-10">
 <input type="text" class="form-control input-validation-error" 
 data-val="true" 
 data-val-required="The Name field is required." 
 id="Name" name="Name" value="">
 <span class="text-danger field-validation-error" 
 data-valmsg-for="Name" 
 data-valmsg-replace="true">The Name field is required.</span>
</div>
Here I'm applying 'required' data- attribute rule which is default validation rule in jQuery Unobtrusive Validation library.

Let's disable the server-side validation by removing the [required] attribute on 'Name' property in the 'Person' Model
//[Required]
public string Name { get; set; }
Now if we test the application, validation will take place in the browser without posting the form to the server.

Need Both Client And Server-Side Validations? :

I suggest having both client and server-side validation makes a more assured way of submitting form data. Client-side validation really cut down a lot of server round-trips and looks more user-friendly. But there might be chances of by-passing client validations and submit data at times server-side help to guard.

Let's enable both client-side and server-side validation in our sample. Update the code as follows
Views/Person/Create.cshtml:
<label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
 <input asp-for="name" type="text" class="form-control" />
 <span asp-validation-for="name" class="text-danger"></span>
</div>
Models/Person.cs:
[Required]
public string Name { get; set; }
Now if you test application, validation will be done by the browser. Let's by-pass javascript by blocking in the browser and now if you test validation will be done at the server-side. So we can understand how cool it is having both client-side and server-side validations.

Block javascript in chrome browser:
Now test application, client-side validation fails since script blocked on the browser, page reload then form gets validated at the server.

Custom Attribute Validation:

We can write custom validation to implement our own logic. This custom validation can be done at the entire model level or particular property in the model. Here we are going to create a property level validation. For our sample, I'm creating a custom validation attribute for the input field value that should match with the string specified in the server.

Attributes/TextMatchAttribute.cs:
using System.ComponentModel.DataAnnotations;
using MvcValidation.App.Models;

namespace MvcValidation.App.Attribute
{
    public class TextMatchAttribute:ValidationAttribute
    {
        public string ExpectedText { get; set; }
        public TextMatchAttribute(string expectedText)
        {
            ExpectedText = expectedText;
        }
        
        public string GetErrorMessage() => $"Enter value should always be {ExpectedText}";

        protected override  ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var person = (Person)validationContext.ObjectInstance;
            if(string.IsNullOrEmpty(person.Name) || person.Name.ToLower() != ExpectedText.ToLower())
            {
                return new ValidationResult(GetErrorMessage());
            }
            return ValidationResult.Success;
        }
    }
}
Our TextMatchAttribute implement ValdiationAttribute (provide by DataAnnotation), then overrides IsValid() method where we write own logic for validation. This custom attribute takes input string, so the user entered value in the form must match with this string.

Now use this custom attribute for 'Name' property in the 'Person' model class.
Models/Person.cs:
[TextMatch("Naveen")]
public string Name { get; set; }
Now test the application and navigate to "https://localhost:44397/person/create" and try to submit the form. You may wonder no client-side validation fired, immediately after hitting submit button page get post server(round-trips) and get server-side validations.

Client-Side Custom Validations:

Let's start by checking input field Html by opening developer tools as below
No data- attributes on the input field, will explain two conclusions. The first thing for custom validation attributes MVC Tag Helper has no idea of which type of data- attributes to be generated. The second thing is jQuery Unobtrusive Validation library contains all default attributes rule names like 'require', 'compare', etc so this explains they don't know how to deal with custom attributes.

Let's update the Html by adding data- attribute manually as below
Views/Person/Create.cshtml:
<div class="form-group row">
 <label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
 <div class="col-sm-10">
  <input asp-for="Name"
      data-val="true"
      data-val-textMatch="Enter value should always be Naveen"
      data-val-textMatch-expectedText="Naveen"
      type="text" class="form-control" />
  <span asp-validation-for="Name" class="text-danger"></span>
 </div>

</div>
  • data-val="true" enables field is ready to validate
  • data-val-textMatch here 'textMatch' is the validation rule that needs to be registered in jQuery Unobtrusive Validation.
  • data-val-textMatch-expectedText here 'expectedText' are like additional parameters in 'textMatch' validation rule
Now we need to write a custom javascript validation and register those methods with jQuery Unobtrusive Validation with data- attribute rule name. Add new js file to hold custom javascript logic
wwwRoot/js/customValidation.Js:
$.validator.addMethod('textMatch', function (value, element, params) {
    var txtValue = $(params[0]).val();
    console.log(txtValue);
    var expectedText = params[1];
    console.log(expectedText);

    if (!txtValue || !expectedText) {
        return false
    }

    return txtValue.toLowerCase() === expectedText.toLowerCase();
});
Here method with data- attribute rule name added to jQuery Unobtrusive Validation. This method holds the logic to custom validation.

Now we need to register this method in jQuery Unobtrusive Validation adaptors as below
wwwRoot/js/customValidation.js:
$.validator.unobtrusive.adapters.add('textMatch', ['expectedText'], function (options) {
    var element = $(options.form).find('input#Name');

    options.rules['textMatch'] = [element, options.params['expectedText']];
    options.messages['textMatch'] = options.message;
});
Views/Person/Create.cshml:
@section Scripts{

    @await Html.PartialAsync("/Views/Shared/_ValidationScriptsPartial.cshtml")
    <script src="~/js/customValidation.js"></script>
}
Now test the application and our form gets validated on client-side without making round-trips to server for validations

Generate data- Html Attributes For Custom Validation  Attributes From Server:

If we recall for Custom Validation for client-side we have added data- Html attributes manually. This can be done from the server-side dynamically with the following 2 approaches.
  • Using AttributeAdapterBase<TAttribute>
  • Using IClientModelValidator

Generate data- Html Attributes Using AttributeAdapterBase:

Attributes/TextMatchAttributeAdapter.cs:
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Localization;

namespace MvcValidation.App.Attribute
{
    public class TextMatchAttributeAdapter : AttributeAdapterBase<textmatchattribute>
    {
        public TextMatchAttributeAdapter(TextMatchAttribute attribute, IStringLocalizer stringLocalizer):base(attribute, stringLocalizer)
        {

        }

        public override void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-textMatch", GetErrorMessage(context));
            MergeAttribute(context.Attributes, "data-val-textMatch-expectedText", Attribute.ExpectedText);
        }

        public override string GetErrorMessage(ModelValidationContextBase validationContext)
        {
            return Attribute.GetErrorMessage();
        }
    }
}
  • AttributeAdopterBase<TAttribute> is extended from Microsoft.AspNetCore.Mvc.DataAnnotations. 
  • The type of this Adapter is our custom validation Attribute. 
  • An override method 'AddValidation' is the place where we add our data- attributes render dynamically on page load
To create the instance of the validation attribute adapter, we need to register it under provider a class that implements Microsoft.AspNetCore.Mvc.DataAnnotations.IValidationAttributeAdapterProvider.
Attributes/CustomValidationAttributeAdapterProvider:
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.Extensions.Localization;

namespace MvcValidation.App.Attribute
{
    public class CustomValidationAttributeAdopterProvider: IValidationAttributeAdapterProvider
    {
        private readonly IValidationAttributeAdapterProvider baseProvider = new ValidationAttributeAdapterProvider();
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if(attribute is TextMatchAttribute textMatchAttribute)
            {
                return new TextMatchAttributeAdapter(textMatchAttribute, stringLocalizer);
            }
            return baseProvider.GetAttributeAdapter(attribute, stringLocalizer);
        }
    }
}
Now register this provider class in the ConfigureServices method in Startup.cs
Startup.cs:
services.AddSingleton<IValidationAttributeAdapterProvider, CustomValidationAttributeAdopterProvider>();
Now remove all manually added data- attributes for custom validations from the Html as below
Views/Person/Create.cshml:
<div class="form-group row">
 <label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
 <div class="col-sm-10">
  <input asp-for="Name" type="text" class="form-control" />
  <span asp-validation-for="Name" class="text-danger"></span>
 </div>

</div>
Now run the application and open developer tools then inspect elements, we can observe data- attributes for custom validation are bound from the server.

Generate data- Html Attribute Using IClientModelIValidator:

To follow this approach let's create a new custom validation attributes(here creating new custom validation attribute for code displaying purpose, if you want you can override previous custom validation attribute with this approach)
Attributes/TextMatch2Attribute.cs:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using MvcValidation.App.Models;

namespace MvcValidation.App.Attribute
{
    public class TextMatch2Attribute : ValidationAttribute, IClientModelValidator
    {
        public string ExpectedText { get; set; }
        public TextMatch2Attribute(string expectedText)
        {
            ExpectedText = expectedText;
        }

        public string GetErrorMessage() => $"Enter value should always be {ExpectedText}";
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-textMatch", GetErrorMessage());
            MergeAttribute(context.Attributes, "data-val-textMatch-expectedText", ExpectedText);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var person = (Person)validationContext.ObjectInstance;
            if (string.IsNullOrEmpty(person.Name) || person.Name.ToLower() != ExpectedText.ToLower())
            {
                return new ValidationResult(GetErrorMessage());
            }
            return ValidationResult.Success;
        }

        private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }

            attributes.Add(key, value);
            return true;
        }
    }
}
Here custom attributes extend  ValidationAttribute class to implement custom validation logic and it also implementing IClientModelValidator which helps to bind data- attributes to the Html.

Update Model class to use this new custom validation attribute as follows
Models/Person.cs:
[TextMatch2("Iron Man")]
public string Name { get; set; }
Now run application and inspect Html elements, we can see data- attributes render to the Html elements.

Dynamic Form Validation Using jQuery Unobtrusive Validation:

Some times we may need to load a form dynamically load the form, for those forms validation will not work like forms loaded on-page. But we have the option to add validation to forms loaded through AJAX call by parsing them by jQuery Unobtrusive Validation.

Add a new action method in PersonController.cs as below
PersonController.cs:
[HttpGet]
[Route("test-page")]
public IActionResult TestPage()
{
 return View("Test");
}
Views/Person/Test.cshml:
<div>
    <div class="row">
        <div class="col col-sm-12">
            <button type="button" class="btn btn-primary" id="loadform">Load Form And Add Dynamic Validations</button>
        </div>
    </div>
    <div class="row" style="margin-top:10px">
        <div class="col col-sm-12">
            <div id="form-container">

            </div>
        </div>
    </div>
    
</div>
@section Scripts{

    @await Html.PartialAsync("/Views/Shared/_ValidationScriptsPartial.cshtml")
    <script src="~/js/customValidation.js"></script>
    <script src="~/js/dynamicForm.js"></script>
}
Here on this page, we have a button on clicking it loads form by AJAX Call and then it will be rendered inside the div with an id of 'form-container'.
wwwRoot/js/dynamicForm.js:
$("#loadform").click(function () {
    $("#form-container").html('');
    $.get({
        url: "https://localhost:44397/person/get-dynamic-form",
        dataType: "html",
        error: function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + ": Couldn't add form. " + errorThrown);
        },
        success: function (newFormHTML) {
            var container = document.getElementById("form-container");
            container.insertAdjacentHTML("beforeend", newFormHTML);
            var forms = container.getElementsByTagName("form");
            var newForm = forms[forms.length - 1];
            $.validator.unobtrusive.parse(newForm);
        }
    })
})
Here we are calling an MVC action method that delivers partial view which contains a form that will be returning as a response. '$.validator.unobtrusive.parse('yourform')' this method helps to parse the form Html and activate the client-side validations.

Now add a new action method in PersonController.cs that delivers partial view
PersonController.cs:
[HttpGet]
[Route("get-dynamic-form")]
public IActionResult DynamicForm()
{
 return PartialView("DynamicPartilForm");
}
Views/Person/DynamicPartilForm.cshtml:
<div>
    <form >
       
        <div class="form-group row">
                <label  class="col-sm-2 col-form-label">Name</label>
                <div class="col-sm-10">
                    <input 
                           id="Name",
                           name="Name"
                           data-val="true"
                           data-val-textMatch="Enter value should always be Naveen"
                           data-val-textMatch-expectedText="Naveen"
                           type="text" class="form-control" />
                    <span class="text-danger field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
                </div>

            </div>
        <div class="form-group row">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>
Now run the application and navigate to "https://localhost:44397/person/test-page" which show as below
Now click on the button we can see dynamic form get rendered at the bottom of the button as below
Now submit the form with an empty input field, we can observe client-side validations get fired

Summary:

We have covered server-side validation and client-side validation and then discussed custom validation attributes creation. we have manually written the logic for custom validation at the client-side with the help of the jQuery Unobtrusive Validation library. We learned about validation sync between server-side and client-side using data- attributes. Finally we hands-on dynamic forms client-side validations.

Refer:


Comments

Popular posts from this blog

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route.

An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below
app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaults:new { …

GraphQL API Integration In Asp.Net Core Application

Introduction:
GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data.
How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions.HTTP-POST is the only Http verb recommended by the GraphQL.The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API:The main building blocks of GraphQL API is Schemas and Types. A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc.Types likely to be called Grap…

ASP.NET Core Web API Versioning

Introduction: An iteration and evolutionary changes of an ASP.NET Core Web API is handled by Versioning. Versioning of an API gives confidence to the clients which consumes API for a long time. Any changes or development of an API will be accessible using the new version and it won't cause issues to the clients consuming the old version of API.
When To Use Versioning:Any API response changes.Developing an API by implementing testing levels like 'Alpha', 'Beta', and 'RC' versions before releasing Production.Deprecating an API which means API going to be removed or upgraded by a version within a short period. Versioning Types:Query String VersioningUrl Path VersioningMedia Type Versioning API Version Nuget: To Configure versioning to AspNet Core Web API Microsoft provided a library(Microsoft.AspNetCore.Mvc.Versioning). So to use the versioning library please install NuGet below.
 Install-Package Microsoft.AspNetCore.Mvc.Versioning -version 4.0.0 Register API V…

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload:The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client. Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file. Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk. If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application.
Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.  Check the link to use the Visual Studio Code for .NET Core Application.
IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files from the client, then the entire …

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items.
The main building block of ion-picker as follows: PickerControllerPickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options
PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker.
Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger", "Lion", "Elephant"…

Blazor WebAssembly Dynamic Form Validation

Introduction: In Blazor WebAssembly(client-side framework) form validation can be done with Data Annotations. Using Data Annotations we can validate form either by default validation attributes or by creating custom validation attributes. Using this Data Annotation attribute we can dynamically add or remove validation on a specific field in a form.
Create Blazor WebAssembly Project: To create a Blazor WebAssembly template project need to install the latest version of VisualStudio 2019 for rich intelligence support or we can use VisualStudio code but less intelligence support from the editor. Click here to know about Blazor WebAssembly template creation. Blazor WebAssembly is in preview mode, not yet ready for production.
Create Razor Component: After creating a sample project using the Blazor WebAssembly template, in "Pages" folder add new Razor Component, name it as "UserForm.razor"
Add Route: In Blazor routing can be configured using @page  directive, and URL should b…

Blazor Server CRUD Operations

Introduction: Blazor Server is a web framework to develop server-side single-page applications. Blazor is made up of components with the combinations on C#, Html, CSS.  Blazor Server is production-ready from the .Net Core 3.0.  Blazor Server Working Mechanism:Blazor Server is a very light-weight web development framework. In Blazor Server, not all code gets downloaded to the client browsers. Blazor Server made of components these components can be a block of code or page with respective navigation. Blazor server application communicates with the server with a SignalR background connection which is inbuilt functionality. Application click,  form submission, change events, application page navigation every operation is carried out by the SignalR connection by communicating with the server. Blazor updates the Html DOM very gently on every data update without any overhead. Blazor Server application maintains a nice intelligent tree structure to update the required information or changed …

NestJS API CRUD Operations With MongoDB

Introduction: NestJS is a framework used to develop server-side applications. NestJS built on top of Node.js frameworks like Express. It is a combination of Progressive Javascript, Object-Oriented Programming, Functional Programming, and Functional Reactive Programming.
Nest CLI Installation: Using Nest CLI we are able to generate the NestJS starter project with the default template. To install Nest CLI globally over our system open command prompt and run the command
npm i -g @nestjs/cli Now create a sample project by using Nest CLI command  nest new your_project_name package.json: Now open the package.json file from the sample application created, you can observe few properties like "scripts", "dependencies", and "devDependencies".
"dependencies" contains all plugins to be installed and used them to run the application.
"devDependencies" contain all plugins to be installed and used them at the time of application development.
"scrip…

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server.
Main Response Caching Headers are like below
Cache-ControlPragmaVary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response.private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores.max-age - this directive represents a time to hold a response in the cache.no-cache - this directive represents no storing of response and always fetch the fresh response from serverno-store…