當我嘗試提交/發佈數據時發生該錯誤...有人可以請幫我試過每篇文章,但他們沒有幫助我。我是新來的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 ... –