Search code examples
c#asp.net-mvcvalidationmodel-view-controllerdropdownlistfor

ASP MVC Validation dropdownbox


I'm using model validation in MVC to validate my forms.

I do it like this:

[MetadataType(typeof(CarModel))]
public partial class Car {...}


public class CarModel
{
    [Required(ErrorMessage = "Select the brand please")]
    [Display(Name = "Brand* :")]
    public object brand_id { get; set; }

    ...
 }

In my View I have this code for the dropdownbox:

@Html.DropDownListFor(m => m.brand_id, new SelectList(ViewBag.brands, "id", "name"), new {@class = "selectBoxes" })

And the Viewbag.brands is filled like this:

List<Brand> brands = Brand.GetAllBrands();
ViewBag.brands = brands;

(Brands has the fields "id" (int) "name" (string)), the Car class/table uses "brand_id" as reference.

When I want to sent an empty form, normally Formvalidation should work, but I get an error on the @Html.DropDownListFor:

ArgumentNullException was unhandled by user code
Value cannot be null.

What is the problem? The creation of the dropdownbox? Or isn't formvalidation working correct? The brand-names are loaded correct in the dropdownbox and there is NO "0" value like (-- Select --), the first brand is displayed in the dropdownbox... But when I send an empty form it gets stuck on the dropdownlist...

EDIT: Maybe the problem is that Car uses "brand_id" and Brand uses "id"? If yes, how to solve this without changing this field-names?

EDIT2: Brand is just a partial class of Brands (Linq), with function:

public static List<Brand> GetAllBrands()
{
    db = new CarsDataClassesDataContext();
    return db.Brands.OrderBy(b => b.name).ToList<Brand>();
 }

Solution

  • Based from your POST method, if the ModelState is invalid it will return to the same view, in which case you will have to reinitialized ViewBag.brands all over again.

    if (ModelState.IsValid)
    {
         // perform your logic here
    }
    
    // if you reached this code, that means the model validation failed
    // so you will have to reinitialize the ViewBag
    
    ViewBag.brands = Brand.GetAllBrands();
    return View(car);