列出<selectlistitem>()for html helper DropDownListFor()

时间:2017-01-08 05:44:23

标签: asp.net-mvc html-helper selectlistitem

我正在尝试生成如下列表 -

@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循环中得到了一个异常。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

Value的{​​{1}}属性为SelectListItem,因此string类型为OutletTypeId,请使用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

生成表单元素