Captain0
Captain0

Reputation: 2613

Validation of child object

I have an object that contains a child object. eg.

public class Person
{
    public string Name { get; set; }
    public Car Car { get; set; }
 }

 public class Car
 {
     public int CarId{get;set;
     public string Name { get; set; }
     public string Year { get; set; }
 }

Then on my Razor view i use a DropDownlistFor, with the list of cars that the user can select. I bind the Dropdownlist like

    @Html.LocalLabelFor(m => m.Person.Car)
    @Html.DropDownListFor(m => m.Person.Car, new SelectList(Model.Cars, "CarID, "Name"), "Select")

When the user does not select a car, then the jquery validation still validates the CarId as not being selected. The car object must be nullable.

I know I can get around this by creating a flat viewmodel.

Is there any other way to make the car optional on the form ?

Upvotes: 2

Views: 680

Answers (2)

VJAI
VJAI

Reputation: 32758

Clear the error from the model state in the controller action

For ex.

[HttpPost]
public ActionResult Save(Person person)
{
      if (person.Car != null && person.Car.CarId == 0)
      {
        if (ModelState.ContainsKey("Car.CarId"))
          ModelState["Car.CarId"].Errors.Clear();
      }

      return View();
}

Upvotes: 0

karaxuna
karaxuna

Reputation: 26930

Just make CarId nullable:

public class Car
 {
     public int? CarId { get; set };
     public string Name { get; set; }
     public string Year { get; set; }
 }

Upvotes: 1

Related Questions