Loading

ASP.NET MVC

What is Remote Validation in ASP.NET MVC when JavaScript is Disabled?. The Complete ASP.NET MVC Developer Course 2023 [Videos].

In this article, I am going to discuss Remote validation in ASP.NET MVC Application when JavaScript is Disabled. Please read our previous article where we discussed Remote validation in the ASP.NET MVC application. In our previous article, we discussed what is Remote Validation and how to implement Remote Validation in MVC. This is a continuation part to our previous article, so please read our previous article before proceeding to this article.

Remote validation in MVC when javascript is disabled:

The Remote attribute only works when JavaScript is enabled. If the end-user disables JavaScript on his/her machine then the validation does not work. This is because RemoteAttribute requires JavaScript to make an asynchronous AJAX call to the server-side validation method. As a result, the user will be able to submit the form, bypassing the validation in place. This is why it is always important to have server-side validation.

To make server-side validation work, when JavaScript is disabled, there are 2 ways

  1. Add model validation error dynamically in the controller action method
  2. Create a custom remote attribute and override IsValid() method
Add model validation error dynamically in the controller action method

Modify the Create action method that is decorated with the [HttpPost] attribute as shown below.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UserID,FullName,UserName,Password")] User user)
{
// Check if the UserName already exists, and if it does, add Model validation error
if (db.Users.Any(x => x.UserName == user.UserName))
{
ModelState.AddModelError("UserName", "UserName already in use");
}
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}

At this point, disable JavaScript in the browser, and test your application. Notice that, we dont get client-side validation, but when we submit the form server-side validation still prevents the user from submitting the form, if there are validation errors.

However, delegating the responsibility of performing validation, to a controller action method violates the separation of concerns within MVC. Ideally, all validation logic should be in the Model. Using validation attributes in models should be the preferred method for validation.

Creating a Custom Remote Attribute

Step1: Right-click on the project name in solution explorer and a folder with the name “Common”
Step2: Right-click on the “Common” folder, you have just added and add a class file with the name RemoteClientServer.cs
Step3: Copy and paste the following code.

namespace RemoteValidationInMVC.Common
{
public class RemoteClientServerAttribute : RemoteAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Get the controller using reflection
Type controller = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller",
this.RouteData["controller"].ToString()).ToLower());
if (controller != null)
{
// Get the action method that has validation logic
MethodInfo action = controller.GetMethods()
.FirstOrDefault(method => method.Name.ToLower() ==
this.RouteData["action"].ToString().ToLower());
if (action != null)
{
// Create an instance of the controller class
object instance = Activator.CreateInstance(controller);
// Invoke the action method that has validation logic
object response = action.Invoke(instance, new object[] { value });
if (response is JsonResult)
{
object jsonData = ((JsonResult)response).Data;
if (jsonData is bool)
{
return (bool)jsonData ? ValidationResult.Success :
new ValidationResult(this.ErrorMessage);
}
}
}
}
return ValidationResult.Success;
// If you want the validation to fail, create an instance of ValidationResult
// return new ValidationResult(base.ErrorMessageString);
}
public RemoteClientServerAttribute(string routeName)
: base(routeName)
{
}
public RemoteClientServerAttribute(string action, string controller)
: base(action, controller)
{
}
public RemoteClientServerAttribute(string action, string controller,
string areaName) : base(action, controller, areaName)
{
}
}
}

Step4: Open â€œUser.cs” file, that is present in â€œModels” folder. Decorate â€œUserName” property with RemoteClientServerAttribute. 

using System.ComponentModel.DataAnnotations;
using RemoteValidationInMVC.Common;
namespace RemoteValidationInMVC.Models
{
[MetadataType(typeof(UserMetadata))]
public partial class User
{
}
public class UserMetadata
{
[RemoteClientServer("IsUserNameAvailable", "Home",
ErrorMessage = "UserName already in use")]
public string UserName { get; set; }
}
}

Disable JavaScript in the browser, and test your application. Notice that, we dont get client-side validation, but when you submit the form server-side validation still prevents the user from submitting the form, if there are validation errors. 

See All

Comments (304 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /304

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /304

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /304