Home > Enterprise >  ASP.NET MVC - Get exception: InvalidOperationException: The model item passed into the ViewDataDicti
ASP.NET MVC - Get exception: InvalidOperationException: The model item passed into the ViewDataDicti

Time:08-06

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  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 >Add</button>
</form>

Thanks for the help.

CodePudding user response:

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());
}
  • Related