我試圖添加一個DropDownList到MVC 查看並不斷收到以下錯誤。點擊表單提交後會發生這種情況。任何人都可以幫助闡明這意味着什麼以及我如何解決它?MVC DropDownList導致表單異常提交
錯誤消息
The ViewData item that has the key 'Amount' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.
爲背景,這裏是我已經設置了模式和查看導致上述錯誤
對於模型.. 。
[Required]
[DataType(DataType.Currency)]
[Display(ResourceType = typeof(Resources.Resources), Name = "ApplicationAmountLabel")]
public string Amount { get; set; }
public IEnumerable<SelectListItem> Amounts { get; set; }
當模型建立,這裏的值是如何設置的?
model.Amounts = GetAmounts();
...
private IEnumerable<SelectListItem> GetAmounts(List<int> amounts)
{
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = string.Empty, Value = "0" });
foreach (var amount in amounts)
{
list.Add(new SelectListItem { Text = amount.ToString("C"), Value = amount.ToString() });
}
return list;
}
最後,這裏是如何在視圖中使用...
@Html.LabelFor(m => m.Amount)
@Html.DropDownListFor(m => m.Amount, Model.Amounts, "-- Select One --")
@Html.ValidationMessageFor(m => m.Amount)
優秀的錯誤消息說這一切。, – RickAndMSFT