on postback, the <select> only posts the selected value (or values if multiple enabled). the option list name/value collection is not included in the post. if you need this collection in post processing, you need to recreate on the post code.
System.NullReferansException:
I would like to insert product but SelectListItem returned true Can you help me? It will make me crazy
Developer technologies | ASP.NET | ASP.NET Core
2 answers
Sort by: Most helpful
-
Bruce (SqlWork.com) 79,106 Reputation points Volunteer Moderator
2024-12-20T14:35:46.36+00:00 -
Raymond Huynh (WICLOUD CORPORATION) 620 Reputation points Microsoft External Staff
2025-07-16T08:42:24.1033333+00:00 Hello @Case Ventil ,
A NullReferenceException in C# means your code tried to use something that hasn’t been set up yet, it’s “null.” In your case, it sounds like you’re working with a
SelectListItem
(probably for a dropdown in a form), and you’re getting this error when you try to insert a product.When you submit your form (a POST request), only the selected value from your dropdown is sent back to the server, not the whole list of options. If your code expects the full list of
SelectListItem
objects to still be there after the form is submitted, it won’t be, they’re gone unless you re-create them in your POST handler.#Here are my recommendations:
- Make sure you re-populate your list of
SelectListItem
in your POST action, just like you do in your GET action. - Don’t assume the list will “stick around” after a form post. It won’t.
#Example:
// GET: Show the form public IActionResult Create() { ViewBag.Categories = GetCategories(); // returns List<SelectListItem> return View(); } // POST: Handle form submission [HttpPost] public IActionResult Create(ProductModel model) { if (!ModelState.IsValid) { ViewBag.Categories = GetCategories(); // You need to do this again! return View(model); } // Save product... return RedirectToAction("Index"); }
If you skip re-populating
ViewBag.Categories
in the POST, your view will throw a NullReferenceException when it tries to render the dropdown.Hope this helps!
- Make sure you re-populate your list of