I´m having problem using validation on DropDownListFor ...
My Model :
public class User
{
...
public virtual int Id{ get; set; }
[Required(ErrorMessage = "Required.")]
public virtual Role Role { get; set; }
}
public class Role
{
public virtual int Id{ get; set; }
[Required(ErrorMessage = "Required.")]
public virtual string Name { get; set; }
}
My Controller:
public ActionResult Edit()
{
ViewBag.Roles = new SelectList(new Repository<Role>().GetAll(), "Id", "Name");
return View();
}
My Edit View(Strongly typed)
@model User
...
@Html.LabelFor(model => model.Role)
@Html.DropDownListFor(model => model.Role.Id, ViewBag.Roles as SelectList, "-- Select --",new { @class = "form radius" })
@Html.ValidationMessageFor(model => model.Role)
All works great, the problem is fired when I tried to Save the User model :
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
...
}
The ModelState.IsValid is always false... Looking inside the ModelState, the the error is in Role.Name key... The error is : The Name field is required
Is there any way to fix that ? How?
Thanks