3

我有以下代码-

看法-

<% 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; }  
}

我不知道为什么它仍然需要列表,尽管不是必需的。我只想根据需要有两个属性。因此,我想知道如何声明或更改该列表为不需要并使我的模型状态有效。

4

3 回答 3

6

我这样做的方式是在我的视图模型中有一个属性,下拉列表将绑定到(可以为空),然后有一个单独的属性,其中包含下拉列表的所有选项。

视图模型属性

public int? CountryId { get; set; }
public IEnumerable<SelectListItem> CountryOptions { get; set; }

看法

<label for="CountryId">Country:</label>
<%: Html.DropDownListFor(x => x.CountryId, Model.CountryOptions, "N/A")%>

注意:"N/A"字符串是默认的空值。

HTH,
查尔斯

附言。这当然是使用 ASP.NET MVC 2

于 2010-05-12T22:40:53.147 回答
0

简单的答案是将其从模型中删除并通过 ViewData 传递。然后,您的模型将包含从列表中选择的值的成员。

于 2010-05-12T21:01:49.623 回答
0

我认为它失败了,因为它不能将单个值 ( "") 强制放入 aSelectListItem中以放入列表中。您只能DropDownSelectList选择一个值。

您可以尝试制作您ChallengesAdminViewModel.DropDownSelectList的字符串类型。然后它将是所选选项的值。SelectListItems用于将选项推送到视图,而不是解析发布的结果。

于 2010-05-12T21:39:15.993 回答