-1

Here is what I did:

In My view model, I wrote the following code:

 public int CategoryID;
    public IEnumerable<SelectListItem> CategoryList
    {
        get
        {
            return new UsersContext()
                .Categories
                .OrderBy(e => e.CategoryName)
                .ToList()
                .Select(e => new SelectListItem { Text = e.CategoryID + " " + e.CategoryName, Value = e.CategoryID.ToString() });
        }
    }

And in my view, I wrote this:

  <div class="editor-field">
    @Html.DropDownListFor(model => model.CategoryID, new SelectList(Model.CategoryList, "Value", "Text")/*, new Dictionary<string, object> { { "data-placeholder", "Choose a sandbox..." }, { "class", "chzn-select" }, { "style", "width:200px;" } }*/)
    </div>

I just can't figure out why it keep throwing the exception. Please brothers I need help on how to fix this.

1 Answers1

-1

A nullRefException tell you that something is null (logic).

I think you have to check if this code return something first.

return new UsersContext() .Categories .OrderBy(e => e.CategoryName) .ToList()

bool isSomethingAvailable = new UsersContext().Categories.Any();

If not, the exception is normal.

dpfauwadel
  • 3,866
  • 3
  • 23
  • 40