The error occurs when i tried to Submit/Post the data... could someone please help i tried every post but they are not helping me. I am new to mvc... any help will be granted here is my code...
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);
}
View
<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>
Model
public class UserProfileCreateViewModel
{
[Required(ErrorMessage="{0} is required")]
[Display(Name="Gender")]
public int GenderID { get; set; }
public IEnumerable<SelectListItem> Gender { get; set; }
}
InvalidOperationException: The ViewData item that has the key 'GenderID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Here i have tried this.... // POST: /UserProfile/Create/
[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);
}
DropDownListFor
function. I think you should be creating a new SelectList somewhere in there... – Timothée Bourguignon