简化SelectList的创建和返回

时间:2018-11-09 15:53:19

标签: c# asp.net asp.net-mvc

我当前使用此代码创建并返回SelectList

SelectListItem resultError = new SelectListItem() { Text = "An Error Has Occured!", Value = "N/A" };
List<SelectListItem> selectList = new List<SelectListItem>
{
      resultError
};
return jsSerializer.Serialize(new SelectList(selectList, "Value", "Text", null).Select(a => new { value = a.Value, text = a.Text }).ToList());

总体而言,这似乎有点多余,尤其是最后一个linq语句。

.Select(a => new { value = a.Value, text = a.Text }).ToList());

如何简化?

1 个答案:

答案 0 :(得分:1)

像这样吗?

    [HttpGet]
    public ActionResult Index()
    {
        var response = new List<SelectListItem>() {
            new SelectListItem {
                Text = "An Error has Occured!",
                Value = "N/A"
            }
        };

        return Json(response, JsonRequestBehavior.AllowGet);
    }