Click here to Skip to main content
15,894,955 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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...
C#
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
HTML
<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
C#
public class UserProfileCreateViewModel
{
   [Required(ErrorMessage="{0} is required")]
    [Display(Name="Gender")]
    public int GenderID { get; set; }

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

Exception
[InvalidOperationException: The ViewData item that has the key 'GenderID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.]
   System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name) +457
   System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +188
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +130
   ASP._Page_Views_UserProfile_Create_cshtml.Execute() in f:\User Database\Company.UserDatabase.WebUI\Views\UserProfile\Create.cshtml:71
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +253
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +147
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +89
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +375
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +90
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
   System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +186
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +44
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronou
Posted
Updated 15-Dec-15 4:06am
v2

1 solution

C#
// create method to return gender list, for example call it as GetGenders()



public ActionResult Create()
{
   model.Gender = GetGenders();
   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");
   }
   //repopulate your SelectList properties if model not valid
   model.Gender = GetGenders();
   return View(model);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900