asp.net-mvc - 虽然不是[必需]列表字段按要求显示,但模型状态由于为空而无效?

标签 asp.net-mvc field required-field

我有以下代码-

查看-

<% Html.BeginForm(); %>
    <div>
<%= Html.DropDownList("DropDownSelectList", new SelectList( Model.DropDownSelectList, "Value", "Text"))%>

Controller -

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
    {
    }
}

View 模型-

public class ChallengesAdminViewModel
{
    [Required]
    public string ApiKey { get; set; }

    [Required]
    public string UserId { get; set; }

    public List<SelectListItem> DropDownSelectList { get; set; }  
}

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

最佳答案

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

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

关于asp.net-mvc - 虽然不是[必需]列表字段按要求显示,但模型状态由于为空而无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2822504/

相关文章:

asp.net-mvc - ActionInvoker.InvokeAction(context, "Method") - 如何将参数传递给调用的方法?

c# - 将特殊字符转换为普通字符

extjs - ExtJS 4 中文本字段的边框

java - 我的方法(被另一个类调用)如何从该类获取变量而不将其作为参数传递?

apache-flex - flex 中的必填字段

php - 使用 PHP 进行表单验证

jquery - 如何从 Web Api .Net 中的 AuthorizeAttribute 检索 POST 参数?

asp.net-mvc - ASP.NET MVC - 使用 IEnumerable 模型插入或更新 View

field - 银条3.2 : How to export db fields of only one Dataobject in a CSV file?