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

StackOverflow https://stackoverflow.com/questions/2822504

Question

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.

Was it helpful?

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

OTHER TIPS

The simple answer would be to remove it from your model and pass it via ViewData instead. Then, your model would contain a member for the value that was selected from the list.

I think it's failing because it can't coerce a single value ("") into a SelectListItem to put into a list. You can only ever have one DropDownSelectList value selected.

You might try making your ChallengesAdminViewModel.DropDownSelectList of type string instead. Then it will be the value of the selected option. SelectListItems are made for pushing options to the view, not parsing the posted result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top