我的网络应用中有注册视图。但是,帐户注册将失败,我的下拉菜单将以红色标出。
这是我的下拉代码:
<div class="editor-label">
@Html.LabelFor(model => model.CompanyId, "Company")
</div>
<div class="editor-field">
@Html.DropDownList("Companies", "<Select Company>")
</div>
以下是视图模型中的关联代码:
[Display(Name = "Company")]
public int? CompanyId { get; set; }
public IEnumerable<SelectListItem> Companies { get; set; }
在返回视图之前,这是控制器中的关联代码:
ViewBag.Companies = new SelectList(db.Companies, "CompanyId", "CompanyName");
在调试时,我发现ModelState.IsValid
返回false,因此重新返回视图(并在我的情况下重新设置ViewBag.Companies
)。
如何完成注册成功?我会在参数中填写每个必填字段。不需要选择公司。 当我没有选择公司时,ModelState.IsValid
返回true并运行代码。但是,我希望用户可以选择与他的公司关联。
感谢。
答案 0 :(得分:3)
为什么在你有更好的方法时需要设置ViewBag.Companies
- 在模型中选择列表?无需使用丑陋的ViewBag
你应该有这样的东西
视图模型
public class RegisterViewModel
{
[Display(Name = "Company")]
public int? CompanyId { get; set; }
public IEnumerable<SelectListItem> Companies { get; set; }
}
控制器
[HttpGet]
public ActionResult Register()
{
RegisterViewModel viewModel = new RegisterViewModel();
viewModel.Companies = new SelectList(db.Companies, "CompanyId", "CompanyName");
return View(viewModel);
}
在视图中
<div class="editor-label">
@Html.LabelFor(model => model.CompanyId, "Company")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CompanyId, Model.Companies, "<Select Company>")
</div>
这将正确绑定服务器上的CompanyId
。
答案 1 :(得分:0)
DropDownList在ASP.Net MVC3中有点奇怪。它不会正确绑定到可枚举的SelectListItem。您需要将绑定的选定选项存储到模型中的基元和单独字段中所有选项的列表中。
<div class="editor-label">
@Html.LabelFor(model => model.CompanyId, "Company")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CompanyId, new SelectList(Model.Companies))
</div>
然后,在您的模型中,将SelectListItems的IEnumerable更改为IEnumerable字符串。
[Display(Name = "Company")]
public string CompanyId { get; set; }
public IEnumerable<string> Companies { get; set; }
最后,在你的控制器中,
ViewBag.Companies = db.Companies;
正如旁注,我建议让你的IEnumerable成为IList。下拉菜单肯定会关注数据的显示顺序,因此您的模型应该反映出来。
答案 2 :(得分:0)
如果所选变量类型不是字符串,则模型状态对于下拉列表始终无效。将CompanyId更改为字符串。您仍然可以使用IEnumerable Companies {get; set;}