【问题标题】:The ViewData item that has the key 'distic_id' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'具有键“distic_id”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable<SelectListItem>”类型
【发布时间】:2023-03-12 04:07:01
【问题描述】:

在我的 MVC 项目中运行时,我在视图中按下编辑选项,此时发生此错误

具有键“distic_id”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable”类型

在我看来代码

@Html.DropDownListFor(m => m.distic_id, Model.disticlist)

型号是

public class city
{
    public List<SelectListItem> disticlist { get; set; }
    public int city_id { get; set; }
    [Required]
    [Display(Name = "enter the  District name")]
    public string city_name { get; set; }
    [Required]
    [Display(Name = "select district ")]
    public int distic_id { get; set; }  
}

【问题讨论】:

标签: asp.net-mvc-4 c#-4.0 razorengine


【解决方案1】:

如果您想在下拉列表中获取城市或地区列表,请参阅以下代码

1) 删除您的代码 2)像这样创建一个模型 3) 如果此下拉菜单用于多个页面,请创建一个控制器,如 CommanController 4)在这个控制器中写一个方法 见下面代码

首先需要像这样创建模型

public class Industry
{
    public string Id { get; set; }
    public string industryName { get; set; }
    public string regexindustry { get; set; }
}
public class IndustryModel
{
    public SelectList industryList { get; set; }
}

在控制器中 两步 1 是创建一个返回类型为 List 的方法 并使用对象在任何 ActionReslut 中调用此方法

ViewBag.list=obj.getIndustryList();

public List<Industry> getIndustryList()
    {
        List<Industry> objindustry = new List<Industry>();
        var connString = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
        SqlCommand sqlComm = new SqlCommand("sp_selIndustryMaster", connString);
        connString.Open();
        sqlComm.CommandType = CommandType.StoredProcedure;
        SqlDataReader sqldr = sqlComm.ExecuteReader();
        int count = 0;
        while (sqldr.Read())
        {
            if (count == 0)
            {
                objindustry.Add(new Industry { Id ="", industryName = "Select Industry" });
                count++;
            }
            else
            {
                objindustry.Add(new Industry { Id = Convert.ToString(sqldr["industryCode"]), industryName = sqldr["subindustry"].ToString() });
            }
        }
        return objindustry;
    }

在视图中

@Html.DropDownListFor(model => model.txtindustry, new SelectList(ViewBag.List, "Id", "industryName", 0))

请使用它,您的问题可能会得到解决,

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 2016-03-21
    • 2014-11-13
    • 2018-07-24
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多