I'm new here on STACKOVERFLOW...
I'm just facing an error during adding a Student in the selected DDL item..
Model 1: Department
public class Department
{
[Key]
public int deptid { get; set; }
public string deptname { get; set; }
public IEnumerable<Student> Student { get; set; }
}
Model 2: Student
public class Student
{
[Key]
public int stdid { get; set; }
public string stdname { get; set; }
public string stdaddress { get; set; }
[ForeignKey("Department")]
public int deptid { get; set; }
public Department Department { get; set; }
}
DepartmentsController:
public class DepartmentsController : Controller
{
// GET: Departments
public ActionResult AddDepartment()
{
return View();
}
[HttpPost]
public ActionResult AddDepartment(Department model)
{
if (ModelState.IsValid)
{
using (DbAccess db=new DbAccess())
{
db.Departments.Add(model);
db.SaveChanges();
}
}
return View(model);
}
}
StudentsController:
public class StudentsController : Controller
{
// GET: Students
public ActionResult AddStudent()
{
DbAccess db = new DbAccess();
SelectList datalist = new SelectList(db.Departments.ToList(), "deptid", "deptname");
ViewBag.deptid = datalist;
return View();
}
[HttpPost]
public ActionResult AddStudent(Student model)
{
if (ModelState.IsValid)
{
using (DbAccess db = new DbAccess())
{
db.Students.Add(model);
db.SaveChanges();
}
}
return View(model);
}
}
Students View:
@model MVC_Practice2.Models.Student
@{
ViewBag.Title = "AddStudent";
Layout = "~/Views/Shared/_Layout.cshtml";
SelectList datalist = ViewBag.deptid;
}
.
.
.
<div class="form-group">
@Html.LabelFor(model => model.deptid, "deptid", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m=>m.deptid,datalist)
@Html.ValidationMessageFor(model => model.deptid, "", new { @class = "text-danger" })
</div>
</div>
So when I add a student in the selected department from DDL I faced the below error:
The ViewData item that has the key 'deptid' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
And the below line highlighted:
@Html.DropDownListFor(m=>m.deptid, datalist)