ChrisC
ChrisC

Reputation: 144

Web API MVC model validation without controller

We're busy writing an app that makes use of on-the-fly validation (onBlur, onClick, etc.) and also validation on form submission. The "on-the-fly" check and form submit re-uses the same code to validate the user's input. This is done via MVC's IValidatableObject interface, which requires you to override the Validate method to house the validation code.

Along with this, I was able to incorporate a Validation Attribute that checks the ModelState before entering the Controller method's actual implementation:

[HttpPost]
[ValidateModel]
public void ValidateMyModel([FromBody] SomeModel model)
{
}

[HttpPost]
[ValidateModel]
public void SubmitMyModel([FromBody] SomeModel model)
{
   // Some code here
}

All of this runs correctly and as expected.

The issue I have is, because one Controller method is specifically catered to run validation (the "on-the-fly" manner) and another is entirely devoted to actually submitting the form, there is no code needed to run inside the Controller method that does pure validation. This ends up with the body of the method being empty. This is not clean code design and yet re-using the validation code via the Attributes is. I'm also rather loathe to just run the "Validate only" scenario with the submission code included because that blurs its purpose.

My question thus is, is there a way in MVC to run the validation on the model, without necessarily declaring a controller method, whilst still being accessible via an asynchronous HTTP request?

Upvotes: 2

Views: 600

Answers (1)

ADyson
ADyson

Reputation: 61819

The only way to have something accessible via a HTTP request in MVC is via a controller method.

You say "This is not clean code", but why? You've got two methods with different purposes which are exposed to the client, but both share the same re-usable code to do the parts which they both need. There's no duplication of business or validation logic that I can see, and no verbose or awkward workarounds.

IMHO it actually works quite nicely as it is, and I wouldn't change your approach.

Upvotes: 1

Related Questions