asp.net-mvc - MVC .NET Razor DropDownList

标签 asp.net-mvc razor html-select

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

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

我的 Controller :

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);

我的 View “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 但显然我错过了一些东西。

最佳答案

尝试转换为 IEnumerable 并使用基于模型的帮助程序

@Html.DropDownListFor(m => m.title,((IEnumerable<SelectListItem>)ViewBag.title))

关于asp.net-mvc - MVC .NET Razor DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862732/

相关文章:

asp.net-mvc - 如何用 Fluent 语法编写 HtmlHelper

c# - 如何验证 MVC 上的 RadioButton?

c# - 存储更新、插入或删除语句影响了意外的行数 (0) EntityFramework

html - 可编辑的个人资料页面

javascript - 为什么有这么多 jquery ajax 文件?

c# - 如何在 asp net 5 中传递 "asp-for"的字符串值

javascript - 如何为模态窗口内呈现的局部 View 添加滚动条

javascript - 在 jquery 中选择选项

javascript - 在 Firefox 中的选择字段上禁用或忽略 mousedown

Jquery访问选择框文本没有值怎么办?