简体   繁体   English

ASP.NET MVC关系模型错误

[英]ASP.NET MVC Relational Model Error

I have a two relational Model first one is Teacher.cs 我有两个关系模型,第一个是Teacher.cs

 public class Teachers
{
    [Key]
    public int TeacherID { get; set; }
    public string TeacherName { get; set; }
    public string TeacherLname { get; set; }
    public int DepartmentID { get; set; }
    public string Image { get; set; }

    public Department Department { get; set; }


}

and second is Department.cs 第二个是Department.cs

public int DepartmentID { get; set; }
    public string DepartmentName { get; set; }
    public string Image { get; set; }

    public List<Teachers> Teachers { get; set; }

When I'm creating a new record, I' choose a Department Name for teacher, and It's adding fine. 创建新记录时,我为老师选择一个部门名称,这很好。 But When I want to Delete a record there is a error like this 但是,当我想删除记录时,会出现这样的错误

The ViewData item that has the key 'DepartmentID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.


Line 32:                                 @Html.DropDownList("DepartmentID", String.Empty)

I don't understand what I need to do. 我不明白我该怎么办。 Can you help me? 你能帮助我吗? Thanks a lot 非常感谢

TeacherController EDIT : TeacherController编辑:

 //
    // GET: /Teachers/Delete/5
    [Authorize(Roles = "A")]
    public ActionResult Delete(int id = 0)
    {
        Teachers teachers = db.Teachers.Find(id);
        if (teachers == null)
        {
            return HttpNotFound();
        }
        return View(teachers);
    }

    //
    // POST: /Teachers/Delete/5
    [Authorize(Roles = "A")]
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Teachers teachers = db.Teachers.Find(id);
        db.Teachers.Remove(teachers);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

When you pass an empty string into Html.DropDownList() it looks for a list of items to populate the dropdownlist from the first parameter in the ViewData collection. 当您将空字符串传递给Html.DropDownList()它将查找要从ViewData集合中的第一个参数填充下拉列表的项目列表。 However, there is already an item in that collection that is of type Int32. 但是,该集合中已经有一个Int32类型的项目。

This is one of the many confusing scenarios that happen when you use Html.DropDownList() rather than using a strongly typed model and Html.DropDownListFor() 这是使用Html.DropDownList()而不是使用强类型模型和Html.DropDownListFor()时发生的许多令人困惑的方案之一

I suggest you do this: 我建议你这样做:

@Html.DropDownListFor(x => x.DepartmentID, Model.Departments)

You will need to populate your model with a Departments object that is a list of Departments 您将需要使用Departments对象填充模型,该对象是Departments的列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM