A.R.
A.R.

Reputation: 15685

MVC4 Disable validation for one action

I am working on an MVC4 project and I have a single action on which I would like validation to be disabled, like so:

[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult AddNewItems(AddNewItemsModel model, string postType)
{ ... }

Even though I have 'ValidateInput(false)' set, the application insists on validating the data, etc. I have stepped through the code, and I have confirmed that this action is being called, but it seems as though the attribute is ignored. Is there some simple alternate way to make this work (especially one that won't require another layer of models, etc.) ?

Upvotes: 2

Views: 1789

Answers (2)

A.R.
A.R.

Reputation: 15685

After doing a lot of research, I have concluded that validation is deeply integrated into the default model binder, and that the ValidateInput attribute is basically ignored by MVC. I will note that using the following in web.config

<system.Web>
  ...
  <httpRuntime requestValidationMode="2.0"/>

Will sometimes remedy the situation, but sometimes not. I noticed that this setting, combined with the 'ValidateInput' attribute is only respected intermittently, which makes it useless IMO. At the end I came up with an action filter, defined as such:

public class ClearModelErrorsAttribute : ActionFilterAttribute
{
  // ---------------------------------------------------------------------------------------
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    ModelStateDictionary msd = filterContext.Controller.ViewData.ModelState;
    foreach (var item in msd.Values)
    {
      item.Errors.Clear();
    }
  }
}

You can see that it is doing a brute force removal of all of the errors (thanks to the inability to turn off validation) and this is working for my particular scenario. Obviously, this isn't the most robust solution (and a hack), but it could be easily modified to work for more specific scenarios.

The new signature of my action is like this:

[HttpPost]
[ValidateAntiForgeryToken]
[ClearModelErrors]
public ActionResult AddNewItems(AddNewItemsModel model, string postType)
{ ... }

And I have removed the items from web.config that are mentioned above.

Upvotes: 1

R&#233;da Mattar
R&#233;da Mattar

Reputation: 4381

If you know which field is not being validated, you can bypass validation like this :

var myForbiddenValue = System.Web.Helpers.Validation.Unvalidated(Request).Form["MyForbiddenField"]

Or you may as well iterate through all properties to unvalidate them. You may need to do that work in a customer model binder.

Upvotes: 0

Related Questions