【问题标题】:Although not [required] List field shows up as required and Model State is not Valid due to it being null?虽然不是 [必需] 列表字段按要求显示,并且模型状态由于它为空而无效?
【发布时间】:2010-05-12 20:26:50
【问题描述】:

我有以下代码-

查看-

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

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

【问题讨论】:

    标签: asp.net-mvc field required-field


    【解决方案1】:

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

    ViewModel 属性

    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

    【讨论】:

    • 指出您应该验证“占位符字段” (CountryId) 的值是下拉列表中的可能值之一 (CountryOptions);否则我认为您可以更改 HTML 以提交完全不同的值。
    【解决方案2】:

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

    【讨论】:

    • 嗯..实际上这就是我所做的......但我只是想知道为什么它是 [required] 字段,即使我没有设置它。
    • @mxmissile - 看看我对 no magic string 版本的回答。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-10
      • 2011-09-28
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多