List<SelectListItem>() for html helper DropDownListFor()



我正在尝试生成一个列表,如下所示-

@using SkyTracker.Models
@model SkyTracker.Models.Outlet
@{
    var outletTypeList = new List<SelectListItem>();
    foreach (var item in ViewBag.OutletTypes)
    {
        //Exception Cannot implicitly convert type 'int' to 'string'
        var newType = new SelectListItem { Text = item.OutletTypeName, Value = item.OutletTypeId };
        outletTypeList.Add(newType);
    }
}

<form method="post" action="@(ViewBag.BaseUrl)OutletManagement/Create?id=@ViewBag.RaId">
    @Html.LabelFor(m => m.OutletTypeId, new { @class="required"})
    @Html.DropDownListFor(m => m.OutletTypeId, outletTypeList, new {required="required" })
</form>

但是我在foreach循环中得到了一个例外。有什么帮助吗?

SelectListItemValue属性是 tyeof string所以如果OutletTypeId是 typeof int,则使用 Value = item.OutletTypeId.ToString()

但是,该代码属于控制器,而不是视图,理想情况下,您应该使用包含属性IEnumerable<SelectListItem> OutletTypeList

public class OutletVM
{
    [Required(ErrorMessage = "Please select an outlet type")]
    public int? OutletTypeId { get; set; } // nullable to protect against under-posting attacks
    public IEnumerable<SelectListItem> OutletTypeList { get; set; }
    ....
}

并在控制器中

OutletVM model = new OutletVM()
{
    OutletTypeList = yourCollection.Select(x => new SelectListItem
    {
        Value = x.OutletTypeId.ToString(),
        Text = x.OutletTypeName
    },
    .... // set other properties of the view model
};
return View(model);

并在视图中

@Html.DropDownListFor(m => m.OutletTypeId, Model.OutletTypeList, "Please select")
@Html.ValidationMessageFor(m => m.OutletTypeId)

另请注意,应删除仅 HTML5 客户端验证new {required="required" },并向绑定到的属性添加RequiredAttribute,以便同时获得客户端和服务器端验证。

还考虑使用

 @using (Html.BeginForm("Create", "OutletManagement", new { id = @ViewBag.RaId }))

生成表单元素

相关内容

  • 没有找到相关文章

最新更新