I have 2 scenarios that I need some help with re validation in my ASP.NET MVC application. I’m aware that having validation within the controller is not ideal, so am looking to keep this elsewhere – perhaps with my models where I can.
1) I have a model with various properties, some of which have validation against them using DataAnnotations. I’m then using the Html helper methods within my view to expose any validation errors against the relevant fields. For the most part, these work as expected. The exception I’ve come up against is where one of the fields in my view is a dropdown list. The first item within my list is empty/blank, the rest are genuine values. The property in my model that this field relates to has the following against it:
[Required(ErrorMessage = "A value from the list is required")]
At present, if I leave the default value in the list (blank) and don’t select a genuine value from the list, I want it to render the validation error message, but it’s currently treating it as if it were a valid value, and passing that validation.
How can I get it to fail validation if that blank/empty list item is submitted?
2) On one of my views, I have a few file upload controls, enabling the user to upload images to the website. These fields are not directly bound to any properties within my model – only the resulting filename’s (once the file has been uploaded, converted, renamed etc.) are then assigned to ‘Filename1’, ‘Filename2’ etc. properties within my model.
So, I am wondering how to best go about validating that these mandatory file uploads? At present I am doing the following for each of the file upload controls, within my controller(!):
HttpPostedFileBase file = null;
file = Request.Files["Filename1"];
if (file != null && file.ContentLength == 0)
ModelState.AddModelError("Filename1", "Image1 is required");
Once this is done for each of the file upload controls, I check if the ModelState is valid:
if (ModelState.IsValid)
I’m sure there must be a better way of performing this validation, and I’d imagine it’s not ideal to have this in the controller, but I’m not sure the best way to handle this.
I’d appreciate any help with these 2 scenarios.
Here is my code (explanations later) :
The form:
The model:
The controller :
1) If you have a null value, your model wont be valid.
2) To avoid Request.Files[“Filename1”]; you can “type” your form (new { enctype = “multipart/form-data” }).
With this, your model will contain the file.
You can add an extension method, for example :
And you can add error from somewhere with ModelState.Merge().
I dont know if it’s a “good thing to do”, but it works pretty well 🙂