[英]Getting System.Web.Mvc.SelectListItem as options of DropDownList
I have a ViewBag.CategoryList
which contains ViewBag.CategoryList = new SelectList(Category.GetCategories());
我有一个
ViewBag.CategoryList
,其中包含ViewBag.CategoryList = new SelectList(Category.GetCategories());
My View:我的看法:
@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" }) @Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList), "Select Category", htmlAttributes: new {@class = "form-control"})
What I'm getting is <option>System.Web.Mvc.SelectListItem</option>
instead of my strings.我得到的是
<option>System.Web.Mvc.SelectListItem</option>
而不是我的字符串。 Debugger shows that the ViewBag does have a list of strings.调试器显示 ViewBag 确实有一个字符串列表。
Edit: Fixed it by replacing the view with:编辑:通过将视图替换为以下内容来修复它:
@Html.DropDownListFor(model => model.Category, (IEnumerable)(ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
actually give a select list instead of a string list from the controller.实际上给出一个 select 列表而不是 controller 中的字符串列表。
ViewBag.CategoryList = Category.GetCategories().Select(r => new SelectListItem()
{
Value = r,
Text = r
})
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList, "Value", "Text"), "Select Category", htmlAttributes: new {@class = "form-control"})
try this尝试这个
var list=Category.GetCategories();
ViewBag.CategoryList = list.Select(i => new SelectListItem
{
Value = i.Id.ToString(),
Text = i.Name
})
and view并查看
@Html.DropDownListFor(model => model.Category, @ViewBag.CategoryList,"Select Category", htmlAttributes: new { @class = "form-control" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.