0

I have a two relational Model first one is 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

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 :

 //
    // 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");
    }
1
  • Fuller code showing the details of the delete might help. Commented Mar 22, 2015 at 18:12

1 Answer 1

1

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. However, there is already an item in that collection that is of type 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()

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.