Rahul Patil
Rahul Patil

Reputation: 142

Issue With Foreign Key in mvc?

When I run this code then get an error

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CourseId'

Model

Student.cs

[Key]
public int Id { get; set; }

public string Name { get; set; }
public int CourseId { get; set; }  
public Course course { get; set; }

Course.cs

public class Course
{ 
    [Key]
    public int CourseId { get; set; }

    public string CourseName { get; set; }
}

StudentController.cs

        public ActionResult Create()
        {
            List<SelectListItem> CourseId = new List<SelectListItem>();
            CourseId.Add(new SelectListItem { Text = "1", Value = "1" });
            CourseId.Add(new SelectListItem { Text = "2", Value = "2" });
            CourseId.Add(new SelectListItem { Text = "3", Value = "3" });
            ViewBag.CourseId = CourseId;
            return View();
        }

        [HttpPost]
        public ActionResult Create(Student stud)
        {
            ViewBag.CourseId = stud.CourseId;
            return View();
        }

create.cshtml

<div class="form-group">
                @Html.LabelFor(model => model.CourseId, "CourseId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model=>model.CourseId,new SelectList(ViewBag.CourseId))
                    @Html.ValidationMessageFor(model => model.CourseId, "", new { @class = "text-danger" })
                </div>
            </div>

Image:

enter image description here

I m still facing this error? help First I run Student Controller it is wrong or not?

Upvotes: 0

Views: 118

Answers (1)

illusiveman
illusiveman

Reputation: 23

You need to supply Course Id as SelectListItem in your get action method.Try this

public ActionResult Create()
{ 
  List<SelectListItem> CourseId = new List<SelectListItem>();
  CourseId.Add(new SelectListItem { Text = "1", Value = "1" });
  CourseId.Add(new SelectListItem { Text = "2", Value = "2" });
  CourseId.Add(new SelectListItem { Text = "3", Value = "3" });
  ViewBag.CourseId = CourseId;
  return View();
}

[HttpPost]
public ActionResult Create(Student stud)
{
  ViewBag.CourseId = stud.CourseId;
  return View();
}

Upvotes: 2

Related Questions