Click here to Skip to main content
15,843,623 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to .Net Core and coding and I am making a web MVC app. Now its going great but I cant seem to get a drop down to work properly. I can the values in the view but when I post back to the controller to create a new part its not passing the Id. Id welcome some feedback on what I am doing wrong:

public IActionResult Create()
            ViewBag._PartTypes = new SelectList(partType.ReturnAllPartTypes(), "Id",   "PartTypeName");
            return View();

<div class="form-group">
    @Html.LabelFor(x => x.PartTypeId)
    @Html.DropDownListFor(model => model.PartTypeId, (IEnumerable<SelectListItem>)ViewBag._PartTypes)

What I have tried:

Ive tried different variations of the fields and different approaches and I am just stumped.
Updated 11-Jul-20 9:13am

1 solution

Your model is empty because you didn't pass anything to the View. Note there is nothing inside the parenthesis:
return View();

So, since you didn't pass anything to the view, your references to "model" in the Razor code will all be null:
@Html.DropDownListFor(model => model.PartTypeId, (IEnumerable<SelectListItem>)ViewBag._PartTypes)

Don't use the ViewBag if you're using MVC. It's just going to confuse you.

The purpose of the Model is to pass any data to the view that renders the HTML any data it needs to build the HTML, including the contents of DropDownList's.
Share this answer

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

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