Emir Bolat
Emir Bolat

Reputation: 1049

ASP.NET MVC - Get exception: InvalidOperationException: The model item passed into the ViewDataDictionary is of type

When I open the page I get this error:

enter image description here

My Codes:

Controller:

[HttpGet]
public ActionResult AddStudent()
{

    List<SelectListItem> classList = new List<SelectListItem>();

    foreach (var item in db.ClassTables.ToList())
    {
        classList.Add(new SelectListItem { Text = item.ClassName, Value = item.Id.ToString()});
    }
    ViewBag.ClassList = classList;
    return View(classList);
}

View:

@model StudentApp.Models.Entity.StudentTable
@{
    ViewData["Title"] = "Add Student";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Add Class</h1>
<form class="form-group" method="post">
    <label>Student Name:</label>
    @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
    <br />
    <label>Class:</label>
    @Html.DropDownListFor(m => m.ClassId, (List<SelectListItem>)ViewBag.ClassList, new { @class = "form-control"})
    <br />
    <button class="btn btn-success">Add</button>
</form>

Thanks for the help.

Upvotes: 0

Views: 1116

Answers (1)

Yong Shun
Yong Shun

Reputation: 51220

From your controller action,

return View(classList);

You are returning the value with the List<SelectListItem> type to the View, while your View is expecting the ViewModel with the StudentTable type.

@model StudentApp.Models.Entity.StudentTable

To fix, return a StudentTable instance for the ViewModel.

return View(new StudentTable());

Suggestion: While the foreach loop can be replaced with:

List<SelectListItem> classList = db.ClassTables
        .Select(x => new SelectListItem 
        { 
            Text = item.ClassName, 
            Value = item.Id.ToString()
        })
        .ToList();

Complete code

using StudentApp.Models.Entity;

[HttpGet]
public ActionResult AddStudent()
{
    List<SelectListItem> classList = db.ClassTables
        .Select(x => new SelectListItem 
        { 
            Text = item.ClassName, 
            Value = item.Id.ToString()
        })
        .ToList();
    
    ViewBag.ClassList = classList;
    return View(new StudentTable());
}

Upvotes: 1

Related Questions