我正在将一个asp.net表单站点转换为mvc,并且下拉列表有问题。
模型摘录:
命名空间adminLte.Models
//然后进一步
[Required(ErrorMessage = "Player Segment Required")]
[Display(Name = "Player Segment")]
public string Segment { get; set; }
public IEnumerable<SelectListItem> PlayerSegmentList { get; set; }
//模型类列表
public IEnumerable<SelectListItem> getPlayerSegmentList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="&Segment=1000",Text="1,000+"},
new SelectListItem{ Value="&Segment=750-999",Text="750-999"},
new SelectListItem{ Value="&Segment=500-749",Text="500-749"},
new SelectListItem{ Value="&Segment=400-499",Text="400-499"}
};
myList = data.ToList();
return myList;
}
控制器:
// ??对此不确定...
playerExtract objModel = new playerExtract();
objModel.PlayerSegmentList = objModel.getPlayerSegmentList();
ViewBag.pSeg = new SelectList(objModel, "SegmentID", "Segment");
html表单
@ Html.LabelFor(model => model.Segment,htmlAttributes:new {@class =“ control-label col-md-2”})
@ Html.DropDownListFor(model => model.Segment,ViewBag.pSeg as SelectList,new {htmlAttributes = new {@id =“ Segment”,@class =“ form-control”}}))
@ Html.ValidationMessageFor(model => model.Segment,“”,新的{@class =“ text-danger”})
//结果 编译错误
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Segment'.
我是MVC的新手,很想念东西-非常感谢您提供的任何帮助!
答案 0 :(得分:1)
您应该使用Model.PlayerSegmentList
作为用于构建选择选项的源集合。因此,将其作为您的Html.DropDownListFor
方法调用的第二个参数传递。
@Html.DropDownListFor(model => model.Segment, Model.PlayerSegmentList,
new { htmlAttributes = new { @id = "Segment", @class = "form-control" } })
在您的控制器代码中,此行也没有任何意义!
ViewBag.pSeg = new SelectList(objModel, "SegmentID", "Segment");
SelectList
的第一个参数必须是集合,而不是您的类对象!那应该给你一个编译时错误!只需删除该行,因为您已经在PlayerSegmentList
属性
所以您清理的控制器代码将是
public ActionResult Create()
{
var vm = new YourVieWModel();
var objModel = new playerExtract();
vm.PlayerSegmentList = objModel.getPlayerSegmentList();
return View(vm);
}
如果您在视图中使用相同的YourViewModel
强力键入视图,那应该可以工作
我还建议使用 P ascal C 作为C#类名/方法名:)