Skip to content Skip to sidebar Skip to footer

How Can I Return An Empty List Instead Of A Null List From A Listboxfor Selection Box In Asp.net Mvc?

controller get action IList inputVoltagesList = unitOfWorkPds.InputVoltageRepository.GetAll.ToList(); pdsEditViewModel.InputVoltageList = inputVoltagesList.Sel

Solution 1:

Either make sure it is initialized in the controller (or model/viewmodel) if null, or perhaps (ugly code though) use the coalesce operator to initialize on the fly if null:

@Html.ListBoxFor(m => m.SelectedInputVoltages, Model.InputVoltageList ?? new List<SelectListItem>())

Solution 2:

If you initialize the list in the view model's constructor then it will always be at least an empty list. Anything which builds an instance of the view model would continue to set the list accordingly.

publicclassSomeViewModel
{
    public List<int> SelectedInputVoltages { get; set; }

    publicSomeViewModel()
    {
        SelectedInputVoltages = new List<int>();
    }
}

This way it will never be null in an instance of SomeViewModel, regardless of the view, controller, etc.

If you always want the view model's property to have a default value, then the best place to put that is in the view model. If that logic is instead placed in the controller or the view then it would need to be repeated any time you want to use it.

Post a Comment for "How Can I Return An Empty List Instead Of A Null List From A Listboxfor Selection Box In Asp.net Mvc?"