Asp.net mvc 如何将dropdownlist中的selectlistitem值绑定到模型中的string属性
这就是我填充dropdownlist和创建html元素的方式 会计控制员:Asp.net mvc 如何将dropdownlist中的selectlistitem值绑定到模型中的string属性,asp.net-mvc,html-helper,Asp.net Mvc,Html Helper,这就是我填充dropdownlist和创建html元素的方式 会计控制员: public ActionResult Index() { ViewBag.Towns = new SelectList(_skrsService.GetTowns(), "Value", "Text", 1); return View(); } ... public List<SelectListItem> Get
public ActionResult Index()
{
ViewBag.Towns = new SelectList(_skrsService.GetTowns(), "Value", "Text", 1);
return View();
}
...
public List<SelectListItem> GetTowns()
{
var list = UnitOfWork.Repository<SkrsIl>().OrderBy(x => x.Adi).Select(x => new SelectListItem()
{
Text = x.Adi,
Value = x.Kodu.ToString()
}).ToList();
return list;
}
我希望这能起作用,但收到错误消息:
“具有键“家乡”的ViewData项的类型为
“System.String”,但必须是“IEnumerable”类型。”
我怎样才能使它正常工作?我只是希望将selectem项值设置为'homightry'属性错误意味着
ViewBag.Towns
为null
。当第二个参数(IEnumerable selectList
)为null
时,该方法期望第一个参数为typeofIEnumerable
由于您在GET方法中分配了它,因此当您提交表单并返回视图,但没有像在GET方法中那样重新填充ViewBag.Towns
的值时,几乎肯定会发生这种情况
作为旁注,使用new SelectList()
是毫无意义的额外开销-它只是在第一个基础上创建另一个IEnumerable
。此外,当您绑定到模型属性时,SelectList
构造函数的第4个参数将被忽略-在内部,该方法将构建一个新的IEnumerable
,并根据绑定到的属性的值设置Selected
属性
您的控制器代码应该是
public ActionResult Index()
{
ViewBag.Towns = _skrsService.GetTowns();
return View(); // ideally you should be returning a model
}
[HttpPost]
public ActionResult Index(YourModel model)
{
if (!ModelState.IsValid)
{
ViewBag.Towns = _skrsService.GetTowns(); // re-populate the SelectList
return View(model);
}
// save and redirect
}
但最好使用包含选择列表属性的视图模型,而不是
ViewBag
,这意味着ViewBag.Towns
的值为null
-请参阅。作为旁注,使用new SelectList()
是毫无意义的额外开销-创建相同的IEnumerable
并且忽略构造函数的第四个参数-是homightry
的值决定了所选内容Hello,你的评论包含的内容超出了我的需要,如果你将此作为答案发布,我很高兴接受你的评论,谢谢!
public ActionResult Index()
{
ViewBag.Towns = _skrsService.GetTowns();
return View(); // ideally you should be returning a model
}
[HttpPost]
public ActionResult Index(YourModel model)
{
if (!ModelState.IsValid)
{
ViewBag.Towns = _skrsService.GetTowns(); // re-populate the SelectList
return View(model);
}
// save and redirect
}