Asp.net mvc 在mvc中的@Html.DropDownList中获取空值
通过在控制器中选择dropdownlist项,我得到了空值。[我在调试模式下看到了] 这是我的密码 控制器Asp.net mvc 在mvc中的@Html.DropDownList中获取空值,asp.net-mvc,html-select,Asp.net Mvc,Html Select,通过在控制器中选择dropdownlist项,我得到了空值。[我在调试模式下看到了] 这是我的密码 控制器 public ActionResult Index() { var jobStatusList = new SelectList(new[] { new { ID = "1", Name = "Full Time" }, new { ID = "2", Name = "Part Time" }, }, "ID", "Name
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
}
看法
在staffRegistrationViewModel中,状态字段中获取空值
谢谢您当前的代码正在呈现一个带有name属性值的下拉元素
jobStatusList
。如果视图模型属性名称为Status
,则模型绑定器不会映射该属性名称,因为名称不匹配
您需要使用名称Status
@Html.DropDownList("Status", ViewData["JobStatusList"] as SelectList)
但是,如果您已经在使用视图模型,我建议添加类型为List
的属性来传递数据,而不是使用ViewData/ViewBag以及DropDownListFor
helper方法
@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;}
}
公共类StaffRegistrationViewModel
{
公共int状态{set;get;}
公共列表状态列表{set;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);
}
public ActionResult Index()
{
变量列表=新列表
{
新建SelectListItem{Value=“1”,Text=“全职”},
新建SelectListItem{Value=“2”,Text=“兼职”}
};
var vm=newstaffregistrationvm{StatusList=list};
返回视图(vm);
}
你能提供我如何添加属性和调用视图下拉列表的列表语法吗。
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);
}