我怎样才能在Asp.net MVC中的ListBoxFor选择框返回一个空列表,而不是一个空列表呢? [英] How can I return an empty list instead of a null list from a ListBoxFor selection box in Asp.net MVC?

查看:333
本文介绍了我怎样才能在Asp.net MVC中的ListBoxFor选择框返回一个空列表,而不是一个空列表呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制器获取动作

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

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

视图模型

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

查看

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

我要当用户没有选择的selectedInputvoltages进入我的岗位控制器动作收到一个空列表为空我怎么得到它来作为一个空列表?

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?

推荐答案

要么确保它在控制器初始化(或模型/视图模型)如果为null,或者(丑code虽然)使用聚结运营商初始化动态,如果空:

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

这篇关于我怎样才能在Asp.net MVC中的ListBoxFor选择框返回一个空列表,而不是一个空列表呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆