I have a two model classes which have relationship of one to many.
public class CycleType
{
[Required(ErrorMessage = "Cycle is required.")]
public int CycleTypeID { get; set; }
[Required(ErrorMessage = "Cycle Type is required.")]
[StringLength(20, ErrorMessage = "Cycle Type may not be longer than 20 characters")]
public string Type { get; set; }
public List<CycleModel> CycleModels { get; set; }
}
public class CycleModel
{
public int CycleModelID { get; set; }
[DisplayName("Cycle Type")]
[Required(ErrorMessage = "Cycle is required.")]
public int CycleTypeID { get; set; }
[Required(ErrorMessage = "Model is required.")]
[StringLength(20, ErrorMessage = "Model may not be longer than 20 characters")]
public string Model { get; set; }
public virtual CycleType CycleType { get; set; }
}
Razor file.
<div class="editor-label">
@Html.LabelFor(model => model.CycleTypeID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CycleTypeID,
(SelectList)ViewBag.CycleType,
"Select Cycle Type",
new { id = "ddlCycleType" })
@Html.ValidationMessageFor(model => model.CycleTypeID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>
1)Fist of my problem is, Validaion function did not fire when I choose select cycle type and it only give error back as
The ViewData item that has the key 'CycleTypeID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
2)Second problem is, When I choose one of the cycle type and put value to model more than 20 characters so that validator could check as I expected. But I get the same error message again.
The ViewData item that has the key 'CycleTypeID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Every suggestion will be appreciated.
Well this is a bug in Asp.net MVC due to which the validations don’t work for DropDownListFor and TextAreaFor extension methods.
You can check the details at http://aspnet.codeplex.com/workitem/8576
So, you will need to make use of HTML.DropDownList instead of DropDownListFor and then your validations will work as expected.
Update
From your controller, pass this
And in View use this
More Update
There is one more work-around for this problem.
Just use your original code of
DropDownListFor. And then just make use of class property in it like followingThis will make the validation work, but it will display the default message of The field is required. But else will work as you expect it to be.
I guess this is a better solution and good one for your requirements.