2

我无法将下拉列表链接到视图中的模型。我收到错误消息:具有键“title”的 ViewData 项的类型为“System.String”,但必须为“IEnumerable”类型,代码如下:

public class FareCustomer
{
    [Required]
    public int title { get; set; }

我的控制器:

List<SelectListItem> titleList = new List<SelectListItem>();
titleList.Add(new SelectListItem { Text = "Non renseigné", Value = "0" });
titleList.Add(new SelectListItem { Text = "Monsieur", Value = "1" });
titleList.Add(new SelectListItem { Text = "Madame", Value = "2" });
titleList.Add(new SelectListItem { Text = "Mademoiselle", Value = "3" });
ViewBag.title = titleList;
//Create a new customer
FareCustomer fareCustomer = new FareCustomer();
fareCustomer.title = 1;
return View("CreateAccount", fareCustomer);

我的观点'CreateAccount'

@model PocFareWebNet.Models.FareCustomer
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    @Html.DropDownList("title")
    <input type="submit" value="Save" />
</fieldset>
}

我尝试应用这里描述的内容:Using the DropDownList Helper with ASP.NET MVC 但显然我错过了一些东西。

4

3 回答 3

2

尝试转换为 IEnumarable 并使用基于模型的助手

@Html.DropDownListFor(m => m.title,((IEnumerable<SelectListItem>)ViewBag.title))
于 2013-11-08T16:07:35.850 回答
2

我发现了我的问题。我使用了 Visual Studio 生成的视图,它已经定义了 ViewBag.Title

@model PocFareWebNet.Models.FareCustomer
@{
   ViewBag.Title = "CreateAccount";
}

这就是为什么错误说类型是字符串并且不能转换为 IEnumerable。

razor 似乎不区分大小写:控制器设置 ViewBag.title 但视图设置 ViewBag.Title 并覆盖来自控制器的 ViewBag.title。

谢谢您的帮助。

于 2013-11-08T18:07:45.003 回答
1

试试这个:

@Html.DropDownListFor(model => model.title, (SelectList)ViewBag.title)

第一个参数将接收您选择的值。

于 2013-11-08T15:35:25.163 回答