//此代码显示错误,即没有类型为// IEnumerable for Companytype的viewdata项目
// RegisterModel中的当前代码
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompName { get; set; }
[Required]
[Display(Name = "Company Type")]
public IEnumerable<SelectListItem> CompTypeList { get; set; }
[Required]
[Display(Name = "Total number of Branches")]
[Range(1,10,ErrorMessage = "The {0} must be at least {1}")]
public int TotalBranches { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
//视图中的当前代码
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.CompName)
@Html.TextBoxFor(m => m.CompName)
</li>
<li>
@Html.LabelFor(m => m.CompTypeList)
@Html.DropDownList("Companytype","-select one-")
</li>
<li>
@Html.LabelFor(m => m.TotalBranches)
@Html.TextBoxFor(m => m.TotalBranches)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
// AccountController注册 private DefaultDBEntities3 db = new DefaultDBEntities3();
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.CompTypeList = new SelectList( "Companytype");
return View();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
非常感谢您的协助
答案 0 :(得分:0)
选择列表项是html.dropdownlist帮助程序的无效参数。它正在寻找一个清单。仅存储viewbag中的数据,并在视图中创建选择列表:
//控制器
public ActionResult Register()
{
ViewBag.CompTypeList = db.Companytype.OrderBy(y => y.Name).ToList();
return View();
}
//视图
@Html.DropDownList("CompanyType", new SelectList(ViewBag.CompTypeList, "Id", "Name"))
这将在视图中正确呈现您的下拉列表并消除您的错误。 Id是列表的值字段,Name是要显示的字段。希望这可以帮助。