首页 文章

在mvc中使用逗号分隔值选择ListBox项?

提问于
浏览
-2

我将选定的ListBox项值保存在逗号分隔的字符串中 .

private string fabricString(IEnumerable<string> fabricsList)
    {
        string str = string.Join(",", fabricsList);
        return str;
    }

例如str =“1,3”

现在在编辑控制器中,我如何根据上面的字符串选择ListBox中的Text .

public ActionResult Edit(int? id)
    {

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        fad_Data fad_Data = db.fad_Data.Find(id);
        fad_Data.sizeList = fad_Data.size.Split(',').ToList().Select(s => new SelectListItem() { Text = s, Value = s });
        if (fad_Data == null)
        {
            return HttpNotFound();
        }
        return View(fad_Data);
    }

使用上面的代码我得到错误

An exception of type 'System.ArgumentNullException' occurred in System.Web.Mvc.dll but was not handled in user code 在线

fad_Data.sizeList = fad_Data.size.Split(',') . ToList() . 选择(s => new SelectListItem(){Text = s,Value = s});

如何做到这一点 .

1 回答

  • 0

    您可能正在尝试将 IEnumerable 分配给导致 ArgumentNullExceptionList<T> 类型 .

    以下代码是一个更安全的版本 .

    public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                fad_Data fad_Data = db.fad_Data.Find(id);
                fad_Data?.sizeList = fad_Data?.size?.Split(',').ToList().Select(s => new SelectListItem() { Text = s, Value = s }).ToList(); // You need to add ToList() at the end.
                if (fad_Data.sizeList == null)
                {
                    return HttpNotFound();
                }
                return View(fad_Data);
            }
    

    var bar = foo?.buz(); 此条件访问可以转换为

    if(foo != null)
    {
       bar = foo.buz();
    }
    

相关问题