当我尝试提交/发布数据时发生该错误...有人可以请帮我试过每篇文章,但他们没有帮助我。我是新来的MVC ...任何帮助将被授予 这里是我的代码...具有键“GenderID”的ViewData项目类型为“System.Int32”,但必须是“IEnumerable <SelectListItem”类型的'
public ActionResult Create()
{
UserProfileCreateViewModel model = new UserProfileCreateViewModel();
model.Gender = _GenderRepository.GetAll()
.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.DESCRIPTION
});
return View(model);
}
[HttpPost]
public ActionResult Create(UserProfileCreateViewModel model)
{
if (ModelState.IsValid)
{
UserProfile user = new UserProfile();
user.GENDER_ID = model.GenderID;
_UserProfileRepository.Add(user);
_UserProfileRepository.Save();
return RedirectToAction("Index", "Home");
}
return View(model);
}
查看
<div class="form-group">
@Html.LabelFor(model => model.GenderID, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.GenderID, Model.Gender, "Select from List", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.GenderID, string.Empty, new { @class = "text-danger" })
</div>
</div>
型号
public class UserProfileCreateViewModel
{
[Required(ErrorMessage="{0} is required")]
[Display(Name="Gender")]
public int GenderID { get; set; }
public IEnumerable<SelectListItem> Gender { get; set; }
}
InvalidOperationException异常:该ViewData的具有键'GenderID'的项目类型为'System.Int32',但必须为'IEnumerable'类型'<SelectListItem>'。
在这里,我想这.... // POST:/用户配置/创建/
[HttpPost]
public ActionResult Create(UserProfileCreateViewModel model)
{
if (ModelState.IsValid)
{
UserProfile user = new UserProfile();
user.GENDER_ID = model.GenderID;
_UserProfileRepository.Add(user);
_UserProfileRepository.Save();
return RedirectToAction("Index", "Home");
}
model.Gender = _GenderRepository.GetAll().Select(x =>
new SelectListItem
{
Value = x.ID.ToString(),
Text = x.DESCRIPTION
});
return View(model);
}
添加您的堆栈跟踪或至少指出引发异常的位置。 –
在View中引发异常@ Html.DropDownListFor(model => model.GenderID,Model.Gender,“从列表中选择”,新的{@class =“form-control”}) –
我很确定你'将错误的参数传递给'DropDownListFor'函数。我认为你应该在那里创建一个新的SelectList ... –