MVC Validation Bypass for Request Request

I have this code in the controller:

[HttpGet] public ActionResult Register(UserRegistrationModel model) { return View(); } 

The reason I like this is because the Register page can be pre-populated with values ​​from the query string created from other pages.

The problem is that when my view gets rendered, it shows validation errors ... Is there a way around it?

+4
source share
3 answers

Typically, when you perform this action, you usually use separate parameters, not a complete model; it looks like this is the model’s middleware, and you can confirm your model for you.

Can you verify, by debugging the action, that ModelState.IsValid is false, and that it has some keys in it, related to the fields of your model, which are invalid? If so, you can try to make ModelState.Clear() before returning the view to prevent validation errors from occurring in this case.

+2
source

Quick answer: try using [ValidateInput (false)] in the "GET" action methods

UPDATE: With asp.net 4, in order to get the framework for validating the ValidateInput attribute, you also need to configure the validation mode in the web.config file.

Set the child of <system.web> following:

 <httpRuntime requestValidationMode="2.0"/> 

Why is a ViewModel needed in GET action methods?

Use default binder.

For example, we have child actions that return partial views related to the complex setup of ViewModels, and we don’t want to explicitly instantiate and rebuild the ViewModel for each Child action.

For example, the “Edit” page for the “Order” page accepts an EditOrderViewModel, which inherits BaseUserViewModel, which, in turn, contains user-displayed data (username, product counter, etc.).

Thus, the action method for returning the edit view looks like this:

 [ValidateInput(false)] [HttpGet] public ViewResult Edit(EditOrderViewModel editOrderVm) { ... return View('Edit', editOrderVm ); } 

Now, while the request to this child action method somehow includes the BaseUserViewModel properties (for example, through the Cookies, Form, and QueryString properties), then the linker will by default create an instance and populate EditOrderViewModel with the entire basic data representation model.

However, when we first load this page, we do not want the verification messages to be displayed in a form that the user has not yet been able to edit ...

Therefore, we turned off model validation for the "GET" request> just make sure you check the "POST" request!

+4
source

I had the same problem, I used the CustomValidation attribute in the model for the Create action, but for another action that requires saving changes to the database, it raised a validation error. so I fixed it by removing the CustomValidation attribute and checking the model only inside the Create action method

0
source

All Articles