为什么 DepartmentID 值没有正确绑定到视图模型的 属性?

Why is the DepartmentID value not being properly bound to the view model's property?

不知道为什么,但是由于某种原因,当我点击提交按钮时,视图模型没有绑定 DepartmentId,我得到一个错误:

Value cannot be null.
Parameter name: value

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

不确定哪个值是空值,因为代码不会中断,而是在点击提交按钮后显示的消息。

我假设是 departmentId 没有正确绑定到 CoursePreReqViewModel 中的 DepartmentID 属性。

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value

查看:

@using (Html.BeginForm("Catalog", "Courses", FormMethod.Post, new { @class = "pure-form pure-form-aligned" }))
{
    @Html.AntiForgeryToken()
    <div class="row">
        <div class="col">
            <input id="myInput" class="form-control" type="text" placeholder="Search..">
        </div>
        <div class="col">
            @Html.LabelFor(model => model.DepartmentId, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.DropDownListFor(model => model.DepartmentId, Model.DepartmentList, "Department", new { @class = "form-control required", id = "department-list" })
            @Html.ValidationMessageFor(model => model.DepartmentId)
            
        </div>
        <div class="col">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>
}

控制器:

[HttpPost]
public ActionResult Catalog(CoursePreReqViewModel viewModel)
{
    DepartmentRepo dRepo;
    CoursesRepo cRepo;
    MajorPreRequisitesRepo reqRepo;

    using (context)
    {
        dRepo = new DepartmentRepo(context);
        cRepo = new CoursesRepo(context);
        viewModel.PopulateDepermentSelectList(dRepo.GetAllDepartments());
        reqRepo = new MajorPreRequisitesRepo(context);
        viewModel.Courses = cRepo.GetAllCoursesAndPreReqsByDepartment(viewModel.DepartmentId);
    }

    return View(viewModel);
}

查看模型:

public class CoursePreReqViewModel
{
    [Required]
    [Display(Name = "")]
    public int DepartmentId { get; set; }
    public IList<Course> Courses { get; set; }
    public IList<MajorPreRequisite> CoursesAndPreReqs { get; set; }
    [Display(Name = "Department: ")]
    public IList<Department> Departments { get; set; }

    public CoursePreReqViewModel() { }

    public SelectList DepartmentList
    {
        get
        {
            return new SelectList(Departments, "Id", "Name");
        }
    }

    public void PopulateDepartmentSelectList(IList<Department> populatedDepartments)
    {
        Departments = populatedDepartments;
    }
}

我可以帮助您保留您拥有的代码,并回答您的问题。

controller/classes:

public class Course
{
    public int CourseId { get; set; }
}
public class MajorPreRequisite
{
    public int MajorPreRequisiteId { get; set; }

}
public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class CoursePreReqViewModel
{
    //Make sure to comment this out -or- put this field in view
    //try this first with your code, before you change code eg using a dictionary
    //[Required]
    //[Display(Name = "")]
    public int DepartmentId { get; set; }
    public IList<Course> Courses { get; set; }
    public IList<MajorPreRequisite> CoursesAndPreReqs { get; set; }
    [Display(Name = "Department: ")]
    public IList<Department> Departments { get; set; }
    public CoursePreReqViewModel() { }
    public Dictionary<string, string> DepartmentList { get; set; }
    public void GetAllCoursesAndPreReqsByDepartment(IList<Course> populateCourses)
    {
        Courses = populateCourses;
    }
}
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Catalog(CoursePreReqViewModel viewModel)
    {
        //Put a breakpoint herre to see departmentid of user choice
        return View();
    }
    public ActionResult Index11()
    {
        CoursePreReqViewModel viewModel = new CoursePreReqViewModel();
        Dictionary<string, string> depts = new Dictionary<string, string>();
        depts.Add("1", "deptOne");
        depts.Add("2", "deptTwo");
        viewModel.DepartmentList = depts;

        IList<Course> courses = new List<Course>();
        courses.Add(new Course { CourseId = 1 });
        courses.Add(new Course { CourseId = 2 });
        viewModel.GetAllCoursesAndPreReqsByDepartment(courses);

        return View(viewModel);
    }

查看:

@model WebApplication4what2.Controllers.CoursePreReqViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index11</title>
</head>
<body>
    @using (Html.BeginForm("Catalog", "Home", FormMethod.Post, new { @class = "pure-form pure-form-aligned" }))
    {
        <div class="row">
            <div class="col">
                <input id="myInput" class="form-control" type="text" placeholder="Search..">
            </div>
            <div class="col">
                @Html.LabelFor(model => model.DepartmentId, htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.DropDownListFor(model => model.DepartmentId, new SelectList(Model.DepartmentList, "Key", "Value"), Model.DepartmentId)
                @Html.ValidationMessageFor(model => model.DepartmentId)
            </div>
            <div class="col">
                <button type="submit" class="btn btn-success">Submit</button>
            </div>
        </div>
    }
</body>
</html>

Sarthak 这是另一个答案:这是 asp.net mvc fiddler https://dotnetfiddle.net/ARdtvr !!!显示名称必须是一个值!!!