Reputation: 246
Selectlist works perfectly for Get
request .however for Post
request it gives null
exception
controller code:
var category = _context.CategoryTbl.ToList();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select Category", Value = "0" });
foreach (var m in category)
{
li.Add(new SelectListItem { Text = m.Name, Value = m.Id.ToString() });
ViewBag.category =li;
}
View code:
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.category, "Value", "Text"), new { @id = "ddlCategory", style = "width: 200px;", @class = "form-control input-lg" })
I'm getting following error :
ArgumentNullException: Value cannot be null. Parameter name: items
Upvotes: 1
Views: 2190
Reputation: 20141
It is related to your POST
action where you also need a ViewBag.category
if you return the same view.
You could either use the way in get method to initial it before return view, or simply use new SelectList(_context.CategoryTbl, "Id", "Name")
,refer to below code:
[HttpPost]
public async Task<IActionResult> MyPostMethodName(Model model)
{
if (!ModelState.IsValid)
{
}
//your post logic
//...
//need a ViewBag.category if you return the same view,
ViewBag.category = new SelectList(_context.CategoryTbl, "Id", "Name", model.Category);
return View(product);
}
Upvotes: 0
Reputation: 239460
Three things:
It's more appropriate to store options as a property on your view model. This gets rid of the problems like this one with dynamics. It's much easier to track down problems when you remain strongly-typed.
You don't need to create a SelectList
. All that's need is an IEnumerable<SelectListItem>
which you already have.
It's preferable to use the SelectTagHelper
here.
Taken together, on your model add:
public IEnumerable<SelectListItem> CategoryOptions { get; set; }
Then in your view:
<select asp-for="Category" asp-items="@Model.CategoryOptions"></select>
Upvotes: 2