- 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.
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.