Search code examples
asp.net-mvcfieldrequired-field

Although not [required] List field shows up as required and Model State is not Valid due to it being null?


I have the following code-

View-

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

ViewModel-

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

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

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

I dont know why it still requires the list although not required. I want to have only two attributes as required. So I wanted to know how do i declare or change that list to be not required and have my Model State Valid.


Solution

  • The way I do it is have a property in my view model that the dropdown will be bound to (which is nullable) and then have a separate property that contains all the options for the drop down.

    ViewModel properties

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

    View

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

    Note: The "N/A" string is the default empty value.

    HTHs,
    Charles

    Ps. This is of course using ASP.NET MVC 2