简体   繁体   中英

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:

在此处输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM