具有键'distic_id'的ViewData项的类型为'System.Int32',但必须是'IEnumerable <selectlistitem>'</selectlistitem>类型

时间:2014-03-12 07:07:20

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

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

  

具有键&#39; distic_id&#39;的ViewData项。属于&#39; System.Int32&#39;但必须是&#39; IEnumerable&lt; SelectListItem&gt;&#39;

在我的视图代码中

@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; }  
}

1 个答案:

答案 0 :(得分:0)

如果您想在下拉列表中获取city或dist列表,请参阅以下代码

1)删除你的代码 2)像这样创建一个模型 3)如果这个下拉列表用于多个页面CREATE ONE CONTROLLER,如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; }
}

在控制器中 第二步是创建一个返回类型为List的方法 并使用object

在任何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))

请使用它,你的问题可能会解决,

相关问题