Asp.net mvc 如何将dropdownlist中的selectlistitem值绑定到模型中的string属性

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

这就是我填充dropdownlist和创建html元素的方式

会计控制员:

      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
时,该方法期望第一个参数为typeof
IEnumerable

由于您在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
}