user3689740
user3689740

Reputation: 3

MVC Validation on HttpGet

I have a Search Form wired to an HttpGet method

[HttpGet]
public ActionResult Search(Filter filters){
{
   ...
}

What I would like to be able to do is modal validation, the way it is done in HttpPost. However, I do not want to use HttpPost method because I want to allow users to be able to bookmark their search results. Filters is my dto.

Is there a way I can raise the validation in the HttpGet method? Like..

 if (!filters.Name.HasValue)
            {
                this.ModelState.AddModelError("Name", "THis is a required    Field...");

or use Data Annotations

public class Filter {
    [Required]
    string Name {get;set;}
...

Not sure if this is the correct way. Again, I am not sure which is the best approach. Any help/advice would be great.

Upvotes: 0

Views: 904

Answers (1)

Rowan Freeman
Rowan Freeman

Reputation: 16358

Yes, this is fine.

Model binding and validation doesn't require the HTTP method to be a POST.

Try to use data annotations where possible. They're clean and elegant. Create your own if needed.

Remember that data-annotated validation should be simple; i.e. check to see if values are populated and meet the most basic of requirements (length, data type). After that more serious validation can take place (if needed).

You'll then need to return an adequate view for showing the user the search results or any problems with the search so that they can try again.

There is not much more I can add to answering your question. Your approach is fine.

Upvotes: 1

Related Questions