【问题标题】:MVC dynamic dropdown list not working,getting error "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'LocID'.'"MVC 动态下拉列表不起作用,出现错误“没有具有键 'LocID' 的 'IEnumerable<SelectListItem>' 类型的 ViewData 项。'”
【发布时间】:2020-01-13 18:14:31
【问题描述】:

我正在尝试使用以下代码绑定数据库中的下拉列表值,但它在视图中抛出错误。我做了多个练习,但无法达到输出。有人可以帮我解决这个问题吗?

错误:

没有具有键“LocID”的“IEnumerable”类型的 ViewData 项。

操作代码:

public ActionResult Add()
{
    List<Location> listObj = new List<Location>();
    {
        listObj = LocDrpDwnList();
    };
    List<SelectListItem> LocList = new List<SelectListItem>();

    foreach(var item in listObj)
    {
        LocList.Add(new SelectListItem
        {
            Text = item.LocationName.ToString(),
            Value = Convert.ToInt32(item.LocID).ToString()
        }) ;
    }

    ViewBag.LocID = LocList;
    return View();
}

从数据库中获取列表值的方法:

public List<Location> LocDrpDwnList()
{
    SqlConnection db = new SqlConnection(conn);
    string query = "SELECT * FROM Location";
    SqlCommand cmd = new SqlCommand(query, db);
    db.Open();
    List<Location> loclist = new List<Location>();
    using (IDataReader dataReader = cmd.ExecuteReader())
    {
        while (dataReader.Read())
        {
            Location obj = new Location();
            if (dataReader["LocID"] != DBNull.Value)
            {
                if (dataReader["LocID"] != DBNull.Value) { obj.LocID = Convert.ToInt32(dataReader["LocID"]); }
                if (dataReader["LocationName"] != DBNull.Value) { obj.LocationName =               (string)dataReader["LocationName"]; }
                loclist.Add(obj);
            }
        }
        return loclist;
    }
}

下拉控件的视图:

 @Html.DropDownListFor(model => model.LocID, (IEnumerable<SelectListItem>)ViewBag.LocID , "Select Location", new { htmlAttributes = new { @class = "form-control" } })

【问题讨论】:

  • 你如何返回model.locID?它是否正在行动中?另外,您的视图使用什么模型?你能告诉我们(相关部分)查看页面吗?

标签: c# asp.net-mvc list drop-down-menu


【解决方案1】:

请将您的控制器操作修改为:

public ActionResult Add()
{
    List<Location> listObj = LocDrpDwnList();
    /*
     // Doesn't hurt populating SelectListItem this way. But you don't need to do this here. 
    List<SelectListItem> LocList = new List<SelectListItem>();

    foreach (var item in listObj)
    {
        LocList.Add(new SelectListItem
        {
            Text = item.LocationName.ToString(),
            Value = Convert.ToInt32(item.LocID).ToString()
        });
    }
    */
    ViewBag.LocID = (string?)null; //Set to some predefined locId selection, so when page is loaded, dropdown will be defaulted to this value.
    ViewBag.LocList = LocList;

    return View();
}

然后将您的视图更新为:

@{
    var LocList = new SelectList(ViewBag.LocList, "Id", "Text");
    string LocId = ViewBag.LocId ?? (string)null;
}

@Html.DropDownList(@LocId, @LocList , "Select Location", new { htmlAttributes = new { @class = "form-control" } })

与其使用 ViewBags,不如使用 ViewModels,如下所示:

public class AddViewModel
{
    public AddViewModel()
    {
        this.LocList = new List<LocationViewModel>();
    }

    public int? LocId { get; set; }
    // Instead of LocationViewModel, you can go with your idea List<SelectListItem> and change controller action and view accordingly.
    public List<LocationViewModel> LocList { get; set; }
}

public class LocationViewModel
{
    public int LocId { get; set; }
    public string LocationName { get; set; }
}

您的控制器操作将是:

public ActionResult Add()
{
    List<Location> listObj = LocDrpDwnList();

    List<LocationViewModel> LocList = new List<LocationViewModel>();

    foreach (var item in listObj)
    {
        LocList.Add(new LocationViewModel
        {
            LocationName = item.LocationName.ToString(),
            LocId  = Convert.ToInt32(item.LocID).ToString()
        });
    }
/*
    ViewBag.LocID = (string?)null; //Set to some predefined locId selection, so when page is loaded, dropdown will be defaulted to this value.
    ViewBag.LocList = LocList;*/

    return View(new AddViewModel{LocList = LocList});
}

你的看法将是;

@using AddViewModel
@Html.DropDownList(m => m.LocId, new SelectList(Model.@LocList, "Id", "Text") , "Select Location", new { htmlAttributes = new { @class = "form-control" } })

【讨论】:

    【解决方案2】:

    我相信您在从下拉列表中选择一个值后尝试在数据库中创建一个条目,如果我没记错,您提到的控制器代码没有 POST 标头,您必须创建另一个控制器与 {HttpPost} 听者同名。

    请找到以下链接供您参考,可能会找到任何帮助。

    https://stackoverflow.com/questions/51551547/asp-mvc-model-entity-validation-does-not-displaying-required-error
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多