我有以下代码-
看法-
<% Html.BeginForm(); %>
<div>
<%= Html.DropDownList("DropDownSelectList", new SelectList( Model.DropDownSelectList, "Value", "Text"))%>
控制器-
public ActionResult Admin(string apiKey, string userId)
{
ChallengesAdminViewModel vm = new ChallengesAdminViewModel();
vm.ApiKey = apiKey;
vm.UserId = userId;
vm.DropDownSelectList = new List<SelectListItem>();
vm.DropDownSelectList.Add(listItem1);
vm.DropDownSelectList.Add(listItem2);
vm.DropDownSelectList.Add(listItem3);
vm.DropDownSelectList.Add(listItem4);
vm.DropDownSelectList.Add(listItem5);
vm.DropDownSelectList.Add(listItem6);
vm.DropDownSelectList.Add(listItem7);
}
[HttpPost]
public ActionResult Admin(ChallengesAdminViewModel vm)
{
if (ModelState.IsValid)//Due to the null dropdownlist gives model state invalid
{
}
}
ViewModel-
public class ChallengesAdminViewModel
{
[Required]
public string ApiKey { get; set; }
[Required]
public string UserId { get; set; }
public List<SelectListItem> DropDownSelectList { get; set; }
}
我不知道为什么它仍然需要列表,尽管不是必需的。我只想根据需要有两个属性。因此,我想知道如何声明或更改该列表为不需要并使我的模型状态有效。