Shafiqul Bari Sadman
Shafiqul Bari Sadman

Reputation: 246

ArgumentNullException: Value cannot be null. Parameter name: items selectlist .net core

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

Answers (2)

Ryan
Ryan

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

Chris Pratt
Chris Pratt

Reputation: 239460

Three things:

  1. 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.

  2. You don't need to create a SelectList. All that's need is an IEnumerable<SelectListItem> which you already have.

  3. 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

Related Questions