Search code examples
c#asp.net-mvcentity-framework-4.1dropdownlistfor

modelstate.isvalid always false


i'm filling a dropdownlist as follow:

@Html.DropDownListFor(model => model.Department.Id, new SelectList(db.PhoenixIKDepartments.ToList(), "Id", "Name"))

I expect to have Id, Code and Name, but there is only Id and ModelState is false.

public class Phoenix_IK_Persons
{      
    [Key]
    public int Id { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(500)]
    public string Surname { get; set; }

    [StringLength(50)]
    public string Registry { get; set; }

    public Phoenix_IK_Departments Department { get; set; }
}

public class Phoenix_IK_Departments
{
    [Key]
    public int Id { get; set; }

    [StringLength(50)]
    [Required(AllowEmptyStrings=false, ErrorMessage="Lütfen Kod Giriniz!")]
    public string Code { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "Lütfen Ad Giriniz!")]
    [StringLength(500)]
    public string Name { get; set; }        
}

Can you please help me fill the dropdownlist properly with Id, Name and Code?

Thank you in advance!


Solution

  • The reason Code and Name aren't being populated on the model is because those fields aren't included and populated in the <form> tag anywhere. This line of code:

    model => model.Department.Id
    

    binds that drop down to that field. If you look at the HTML generated you will notice that the name and id attributes are indicative of that.

    However, if you simply put in two hidden fields like this:

    @Html.HiddenFieldFor(model => model.Department.Code);
    @Html.HiddenFieldFor(model => model.Department.Name);
    

    they would get posted back with values. If you needed them to have a values you can simply assign them in JavaScript and when they are posted back they will be assigned to the model.