Tech Point Fundamentals

Sunday, December 11, 2022

.Net Core Interview Questions and Answers - Part 15

ASP.Net Core Interview Questions and Answers - Part 15


Are you preparing for the .Net Core Interview? If yes, then you are at the right place. This is the ASP.Net Core Interview Questions and Answers article series. Here we will see the Top 150+ .Net Core Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:

Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.


This is the 15th part of the .Net Core Interview Questions and Answers article series. Each part contains ten .Net Core Interview Questions. Please read all the .Net Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:

ASP.Net Core Interview Questions and Answers - Part 15

Q145. What are the different built-in validation attributes available in ASP.Net MVC Core?

There are the following built-in validation attributes:

[Required]: Validates that the field isn't null. See [Required] attribute for details about this attribute's behavior.

[ValidateNever]: Indicates that property or parameter should be excluded from validation.

[Compare]: Validates that two properties in a model match.

[RegularExpression]: Validates that the property value matches a specified regular expression.

[Url]: Validates that the property has a URL format.

[StringLength]: Validates that a string property value doesn't exceed a specified length limit.

[Remote]: Validates input on the client by calling an action method on the server.

[Phone]: Validates that the property has a telephone number format.

[EmailAddress]: Validates that the property has an email format.

[CreditCard]: Validates that the property has a credit card format. Requires jQuery Validation Additional Methods

public string Description { get; set; } = null!;

Validation attributes let you specify the error message to be displayed for invalid input as well:

[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]

Internally, the attributes call String.Format with a placeholder for the field name and sometimes additional placeholders.

Q146. How can you display validation errors in ASP.Net Core applications? What is the difference between asp-validation-summary and asp-validation-for tag helpers?

The asp-validation-summary Tag Helper is used to show the validation errors that have been added in the Action method. Add this Tag Helper to a new div control in the View and you will see all the recorded validation errors:

<div asp-validation-summary="All" class="text-danger"></div>

The asp-validation-summary Tag Helper is applied on the div so the validation errors will be shown on this element. 

It is also more useful to display the Model Validation Error Messages alongside the controls that contain the problematic data. This you can achieve by using the asp-validation-for tag helper.

<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>

Q147. What is the difference between Client-Side and Server-Side Validation?

Validations can be performed on both the server side and the client-side ( web browser). The user input validation takes place on the Server Side during a post-back session is called. 

Server-Side validation and the user input validation that takes place on the Client Side (web browser) is called Client-Side Validation. 

Server-Side Validation:

In Server-Side Validation, the input submitted by the user is being sent to the server and validated using one of the server-side scripting languages such as ASP.Net, PHP, etc. 

After the validation process on the Server Side, the response feedback is sent back to the client by a new dynamically generated web page. 

This means that the Model is passed back to the server where the validation is performed according to your Data Annotations and then a result is returned to the user. 

It is better to validate user input on Server Side because you can protect against malicious users, who can easily bypass your Client-Side scripting language and submit dangerous input to the server.

Client-Side Validation:

Client-Side validation does not require a postback. If the user request requires server resources to validate the user input, you should use Server Side Validation. If the user request does not require any server resources to validate the input, you can use Client Side Validation.

Client-Side validations happen on the browser itself and are instant as there is no round trip to the server. They are also called unobtrusive client-side validation and are done by jQuery with is a library of JavaScript. In order to perform Client-Side Validation, you need to add 3 files to your application, these are jQuery, jQuery Validation, and jQuery Validation Unobtrusive.

In Client-Side Validation, you can provide a better user experience by responding quickly at the browser level. When you perform a Client-Side Validation, all the user inputs are validated in the user's browser itself. 

Client-Side validation does not require a round trip to the server, so the network traffic which will help your server perform better. This type of validation is done on the browser side using script languages such as JavaScript, VBScript, or HTML5 attributes.


The Client-Side validations cannot work on properties that have [Range] validation attributes dealing with bool.

The Client-Side Validation will not work for your Custom Model Validation Attributes like the [CustomDate] and [NameValidate]. For these, you have to create Custom Client-Side Validator. 

Q148. What is Remote Validation in ASP.Net Core?

The [Remote] attribute implements client-side validation that requires calling a method on the server to determine whether field input is valid.

Remote Validations are asynchronous validations, although look like Client-Side validations, but are done on the server by AJAX. 

The Remove Validations are performed in the background and the user doesn’t have to click the submit button and then wait for a new view to be rendered on the browser.

To create a Remote Validation you need to add an action method that returns the JsonResult object and has a parameter whose “name is the same” like the “name of the property” it is applied to.

public JsonResult ValidateDate(DateTime DOB)
if (DOB > DateTime.Now)
return Json("Date of Birth cannot be in the future");
else if (DOB < new DateTime(1980, 1, 1))
return Json("Date of Birth should not be before 1980");
return Json(true);

After this you can use this attribute:

[Remote("ValidateDate", "Employee")]
 public DateTime DOB { get; set; }

Q149. What is the behavioral difference of [Required] attribute from ClientSide to Server Side validation?

Actually, the [Required] data annotation validation attribute behaves differently on the client side and server side.

On the server side, a required value is considered missing if the property is null. A non-nullable field is always valid, and the [Required] attribute's error message is never displayed.

However, model binding for a non-nullable property may fail, resulting in an error message such as The value '' is invalid

To specify a custom error message for server-side validation of non-nullable types, you have the following options:

  1. Make the field nullable. Nullable<T> value types are treated like standard nullable types.
  2. Specify the default error message to be used by model binding.

.AddMvcOptions(options =>
options.MaxModelValidationErrors = 50;
_ => "The field is required.");

<IValidationAttributeAdapterProvider, CustomValidationAttributeAdapterProvider>();

On the client side, the non-nullable types and strings are handled differently on the client compared to the server. 

On the client:

  1. A value is considered present only if the input is entered for it. Therefore, client-side validation handles non-nullable types the same as nullable types.
  2. A Whitespace in a string field is considered valid input by the jQuery Validation required method. Server-side validation considers a required string field invalid if only whitespace is entered.

So as we know that non-nullable types are treated as though they had a [Required(AllowEmptyStrings = true)] attribute. 

That means you get client-side validation even if you don't apply the [Required(AllowEmptyStrings = true)] attribute. But if you don't use the attribute, you get a default error message. To specify a custom error message, use the attribute.

Q150. How to assign a null value to the DateTime object?

DateTime is a non-nullable value type. For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue, because it is a value type rather than a reference type.

You can set a nullable DateTime, like the following:

DateTime? nullableDateTime = null;

Or you can also use the longer form: 

Nullable<DateTime> nullableDateTime = null;

You can check the value with HasValue:

if (nullableDateTime.HasValue)

Q151. What is the use of the nullable Required attribute? Why do we need this?

The validation system treats non-nullable parameters or bound properties as if they had a [Required(AllowEmptyStrings = true)] attribute. 

By enabling Nullable contexts, MVC implicitly starts validating non-nullable properties or parameters as if they had been attributed with the [Required(AllowEmptyStrings = true)] attribute.

Case 1: DateTime DataType Property

[Required(ErrorMessage = "Please enter your Date of Birth")]
public DateTime DOB { get; set; }

There is no need to apply any validation attribute for the DOB field which is of type DateTime. This is because the DateTime field has a default value of 01-01-0001 00:00:00 so when the user does not fill any value to this field then this default value will be used, thus making the [Required] attribute useless.

So in such a case an error message: The value ” is invalid will be shown.

However, if you still want to apply [Required] to work on this field then make it a nullable type like:

[Required(ErrorMessage = "Please enter your Date of Birth")]
public DateTime? DOB { get; set; }

In the above code, I have applied the [Required(ErrorMessage = "Please enter your Date of Birth")] attribute so it ensures that the values for the DOB field cannot be empty and should be in proper date format.

Again all the validation for DateTime types cannot be done from the Data Annotations like preventing selecting a future date or allowing min and mix dates. You will have to do it in the Action method or by making a Custom Model Validation Attribute. 

if (jobApplication.DOB > DateTime.Now)
ModelState.AddModelError(nameof(jobApplication.DOB), "Date of Birth cannot be in the future");
else if (jobApplication.DOB < new DateTime(1980, 1, 1))
ModelState.AddModelError(nameof(jobApplication.DOB), "Date of Birth should not be before 1980");

Case 2: Bool DataType Property

Similarly, we cannot use the [Required] attribute and force the user to check the checkbox because this field is of type bool. 

This means a default value of false will be sent if the checkbox is not checked, thus making the Required attribute useless.

 [Required(ErrorMessage = "You must accept the Terms")]
 public bool TermsAccepted { get; set; }

To work around it, I have used the [Range] attribute and provided a type of bool as the value for its first parameter. I have also set both the min and max values as true and thus forcing the user to check the checkbox.

 [Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the Terms")]
 public bool TermsAccepted { get; set; }

Case 3: String DataType Property

Non-nullable types and strings are handled differently on the client compared to the server.

public string Name { get; set; }

If the app was built with <Nullable>enable</Nullable>, a missing value for Name in a JSON or form post results in a validation error. 

So in that case you need to use a nullable reference type to allow null or missing values to be specified for the Name property:

 public string? Name { get; set; }

This behavior can be disabled by configuring SuppressImplicitRequiredAttributeForNonNullableReferenceTypes in Program.cs:

 options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

It applies to ASP.NET Core versions 3.0, 3.1, 5.0, and 6.0 only. It is basically used to get or set a value that determines if the inference of RequiredAttribute for properties and parameters of non-nullable reference types is suppressed. 

If false (the default), then all non-nullable reference types will behave as if [Required] has been applied. If true, this behavior will be suppressed; nullable reference types and non-nullable reference types will behave the same for the purposes of validation.

This option controls whether MVC model binding and validation treat nullable and non-nullable reference types differently. By default, MVC will treat non-nullable reference type parameters and properties as if [Required] has been applied, resulting in validation errors when no value was bound.

MVC does not support non-nullable reference type annotations on type arguments and type parameter constraints. The framework will not infer any validation attributes for generic-typed properties or collection elements.

Q152. How can you disable client-side validation in ASP.Net Core MVC?

There are multiple ways to disable the client-side validations in ASP.Net Core.

The following code disables client validation in Razor Pages:

.AddViewOptions(options =>
options.HtmlHelperOptions.ClientValidationEnabled = false;

Other options to disable client-side validation:

  1. Comment out the reference to _ValidationScriptsPartial in all the .cshtml files.
  2. Remove the contents of the Pages\Shared_ValidationScriptsPartial.cshtml file.

The preceding approach won't prevent client-side validation of the ASP.NET Core Identity Razor Class Library. 

Q153. What is Razor Page in .Net Core?

Razor pages are the next evolution of traditional ASP.Net WebForms. ASP.Net Core Razor Page is very similar to ASP.NET MVC’s view pages. The file extension of razor pages is also .cshtml. The major difference is that in an MVC application model and controller code is included or bonded with View pages. Razor Pages vs MVC in .Net Core

Razor Pages is a new aspect of ASP.NET Core MVC introduced in ASP.NET Core 2.0. It offers a “page-based” approach for building server-side rendered apps in ASP.NET Core and can coexist with “traditional” MVC or Web API controllers.

It is a new feature of ASP.NET Core that makes coding page-focused scenarios easier and more productive. The Razor Pages are lightweight and very flexible for building dynamic, data-driven websites with a clean separation of concerns.

Razor pages start with a @page directive. This means that it handles requests directly without the need to go through the controller. Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views. 

Razor Pages is enabled in Program.cs file:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

AddRazorPages adds services for Razor Pages to the app while MapRazorPages adds endpoints for Razor Pages to the IEndpointRouteBuilder. 

Q154. What is the @page directive in ASP.Net Core MVC?

The @page directive has different effects depending on the type of file where it appears. 

The .cshtml file indicates that the file is a Razor Page.  It specifies that a Razor component should handle requests directly.


It is the same as the Razor view file of traditional MVC. What makes it different from the traditional MVC view is the @page directive. @page makes the file into an MVC action, which means that it handles requests directly, without going through a controller. 

The @page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs. Razor Pages file names have a .cshtml suffix.

If you see the .cshtml.cs code-behind file:


By convention, the PageModel class file has the same name as the Razor Page file with .cs appended. By convention, the PageModel class is called <PageName>Model and is in the same namespace as the page.

The OnGet() method is used to initialize the state needed for the page. OnPost() method is used to handle form submissions. The page has an OnPostAsync handler method, which runs on POST requests.

The PageModel class allows the separation of the logic of a page from its presentation. It defines page handlers for requests sent to the page and the data used to render the page. This separation allows Unit testing and Managing of page dependencies through dependency injection.

Q155. What is the use of the Pages folder in ASP.Net Core MVC?

The Page folder contains Razor pages and supporting files. Actually, each Razor page is a pair of files:

  1. A .cshtml file that has HTML markup with C# code using Razor syntax.
  2. A .cshtml.cs file that has C# code that handles page events.

By convention, the PageModel class file has the same name as the Razor Page file with .cs appended. The file containing the PageModel class is named like Pages/Index2.cshtml.cs.

Supporting files have names that begin with an underscore for example _Layout.cshtml.

The associations of URL paths to pages are determined by the page's location in the file system. The runtime looks for Razor Pages files in the Pages folder by default. The index is the default page when a URL doesn't include a page.

With Razor Pages, you have one Razor file (.cshtml), and a code-behind file (.cshtml.cs) for a single page. However, you can separate your code from the code behind the file with .cshtml.cs extension.

To Be Continued Part-16...

Recommended Articles

Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.


No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.