-->

How can I return an empty list instead of a null l

2019-07-22 04:43发布

问题:

controller get action

IList<InputVoltage> inputVoltagesList = unitOfWorkPds.InputVoltageRepository.GetAll.ToList();

pdsEditViewModel.InputVoltageList = inputVoltagesList.Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() }); 

ViewModel

    public IEnumerable<SelectListItem> InputVoltageList { get; set; }
    public List<int> SelectedInputVoltages { get; set; }

View

    @Html.ListBoxFor(m => m.SelectedInputVoltages, Model.InputVoltageList)

I want to receive a null list when a user makes no selections the selectedInputvoltages comes into my post controller action as null how do I get it to come in as an empty list?

I like both answers is there any benefit in using one over the other?

回答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>())


回答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.

public class SomeViewModel
{
    public List<int> SelectedInputVoltages { get; set; }

    public SomeViewModel()
    {
        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.



回答3:

This is an older post, but this is how I handled returning an empty list.

    private List<StockFundamental> GetEmptyList()
    {
        StockFundamental stockFund = new StockFundamental();
        List<StockFundamental> stockFundList = new List<StockFundamental>();
        stockFundList.Add(stockFund);
        return stockFundList;
    }