在mvc中获取@Html.DropDownList中的空值

getting null value in @Html.DropDownList in mvc

我通过在控制器中选择下拉列表项得到空值。[我在调试模式下看到]

这是我的代码

控制器

public ActionResult Index()
{
    var jobStatusList = new SelectList(new[] 
    {
        new { ID = "1", Name = "Full Time" },
        new { ID = "2", Name = "Part Time" },
    },
    "ID", "Name", 1);

    ViewData["JobStatusList"] = jobStatusList;
}

public ActionResult Create(StaffRegistrationViewModel staffRegistrationViewModel)
{
    //Here is my code
}

查看

@using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{   
    @Html.AntiForgeryToken()
    @Html.DropDownList("jobStatusList",ViewData["JobStatusList"] as SelectList)
}

在 staffRegistrationViewModel 中,状态字段中的值为空。

谢谢

您当前的代码正在呈现具有 name 属性值 jobStatusList 的下拉元素。如果您的视图模型 属性 名称是 Status,它将不会被模型绑定器映射,因为名称不匹配。

您需要呈现名称为 Status

的 SELECT 元素
@Html.DropDownList("Status", ViewData["JobStatusList"] as SelectList)

但是如果您已经在使用视图模型,我建议添加类型为 List<SelectListItem> 的 属性 来传递数据,而不是将 ViewData/ViewBag 与 [=18] 一起使用=] 辅助方法。

@model StaffRegistrationViewModel 
@using (Html.BeginForm("Create", "StaffRegistration"))
{
   @Html.DropDownListFor(a=>a.Status,Model.StatusList)
}

假设您的视图模型有一个 StatusList 属性

public class StaffRegistrationViewModel 
{
   public int Status { set;get;}
   public List<SelectListItem> StatusList { set;get;}
}

并且您的 GET 操作将列表加载到此 属性

public ActionResult Index()
{
    var list = new List<SelectListItem>
    {
        new SelectListItem {Value = "1", Text = "Full Time"},
        new SelectListItem {Value = "2", Text = "Part Time"}
    };
    var vm=new StaffRegistrationVm { StatusList=list };
    return View(vm);
}