我有以下的代碼 -雖然[必填]列表字段根據需要顯示,並且模型狀態由於爲空而無效?
查看 -
<% 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; }
}
我不知道爲什麼它仍然需要在列表雖不需要。我想根據需要只有兩個屬性。所以我想知道如何聲明或更改該列表以使其不是必需的並且具有我的模型狀態有效。
指出您應該驗證您的「佔位符字段」('CountryId')的值是下拉列表中可能的值之一('CountryOptions');否則我認爲你可以改變HTML來提交一個完全不同的值。 – drzaus 2014-04-04 20:44:54