下拉菜单,造成无效的模型状态。 ASP.NET MVC 3 [英] Drop-Down Menu Causing Invalid Model State. ASP.NET MVC 3

查看:127
本文介绍了下拉菜单,造成无效的模型状态。 ASP.NET MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的web应用程序的注册视图。然而,帐号注册将不会成功,我的下拉菜单中会以红色列出。

I have a registration view in my web app. However, account registration would be unsuccessful and my drop-down menu would be outlined in red.

下面是我的下拉code:

Here is my drop down code:

<div class="editor-label">  
   @Html.LabelFor(model => model.CompanyId, "Company")  
</div>   
<div class="editor-field">  
   @Html.DropDownList("Companies", "<Select Company>")  
</div>

下面是我的相关code。在视图模型:

Here is my associated code in the view model:

[Display(Name = "Company")]    
public int? CompanyId { get; set; }

public IEnumerable<SelectListItem> Companies { get; set; }

下面是在控制器我相关的code才返回的观点:

Here is my associated code in the controller before I return the view:

ViewBag.Companies = new SelectList(db.Companies, "CompanyId", "CompanyName");

当我调试,我发现 ModelState.IsValid 返回false,因此重新返回视图(并重新设置 ViewBag.Companies在我的情况)。

As I debug, I find that ModelState.IsValid returns false, and therefore re-returns the view (and re-sets ViewBag.Companies in my case).

我如何成功完成注册?我的参数范围内填写每个必填字段。它不要求选择的公司。 :当我不选择一个公司, ModelState.IsValid 返回true,并通过code运行。不过,我想用户必须与他的公司相关联的选项。

How do I complete a successful registration? I do fill out each required field within parameters. It is not required to select company. When I do not select a company, ModelState.IsValid returns true and runs through the code. However, I would like the user to have the option to associate with his company.

感谢。

推荐答案

为什么你会需要在设置 ViewBag.Companies ,当你有更好的方法 - 有选择列出到模型?无需使用难看ViewBag

Why would you need setting ViewBag.Companies, when you've got the better approach - having select list into the model? No need to use ugly 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 在服务器上正确。

This will bind your CompanyId on server correctly.

这篇关于下拉菜单,造成无效的模型状态。 ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆