How can I return an empty list instead of a null list from a ListBoxFor selection box in Asp.net MVC?

浪子不回头ぞ 提交于 2020-01-04 06:44:47

问题


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;
    }


来源:https://stackoverflow.com/questions/19732667/how-can-i-return-an-empty-list-instead-of-a-null-list-from-a-listboxfor-selectio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!