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
- Add model validation error dynamically in the controller action method
- 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.
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.
Step4: Open “User.cs†file, that is present in “Models†folder. Decorate “UserName†property with RemoteClientServerAttribute.
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.