我有兩個模型類有一對多的關係。@ Html.ValidationMessageFor沒有按預期工作
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文件。
<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)我的問題的拳頭,Validaion功能沒有火的時候,我選擇選擇循環型,而且只給回錯誤的
The ViewData item that has the key 'CycleTypeID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
2)第二個問題是,當我選擇一個的循環類型,並把值設置爲超過20個字符,以便驗證器可以按照我的預期進行檢查。但是我又收到了同樣的錯誤信息。
The ViewData item that has the key 'CycleTypeID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
每個建議將不勝感激。
感謝您的有益解決方案@Pankaj Upadhyay。我認爲HTML.DropDownList無法加載像「(SelectList)ViewBag.CycleType」的數據集合。所以你可以告訴我最好的解決方案。 – 2012-01-12 06:43:52
我已經用DropDownList的用法更新了答案。讓我知道如果它不起作用。目前無法在我的系統上進行測試 – 2012-01-12 06:55:24
非常感謝你@Pankaj Upadhyay,這是工作,但其中一個問題是無法根據現有值動態選擇其中一項。我可以通過使用「@ Html.DropDownListFor(model => model.CycleTypeID, ...」。謝謝 – 2012-01-12 07:10:34