0

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.

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.