views:

377

answers:

2

Hello everybody,

I have

[DisplayName("Country")]
public List<SelectListItem> Countries { get; set; }

property in strong-type Model View class for DropDownList.

When I try to check if the ModelState.IsValid on form postback it's always false & error for Countries tells "Can't convert [value] to SelectListItem" or some of a kind.

I figured out there is no straight-forward mapping for drop down selected value (looks like I'll have to read value from Form value collection), but how can I ignore binding and validation for List property? I just want to make ModelState.IsValid attribute to be true if all the other fields are populated properly.

Thank you in advance

A: 

Is it because the value submitted is of type String or Country rather than a list of SelectListItem or List<SelectListItem>.

What are you binding to the control in the UI?

try

[DisplayName("Country")]
public List<Country> Countries { get; set; }

Where Country is the type name from your DAL.

EDIT: Based on the error you are recieving, it sounds like the model is expecting the value to be a String so try swapping List<Country> for List<String>.

[DisplayName("Country")]
public List<Country> Countries { get; set; }
Greg B
still the same ModelState error. Can't convert from string to Country
Andrew Florko
So it needs to be a String then. The error message is telling you what you need to do.
Greg B
But it can't be a string, because it's a list of something :)I abandoned my attempts to use DropDownListFor and use DropDownList with [name] attribute that points to a string property in view model
Andrew Florko
A: 

Finally I used workaround.

My model now:

class Model
{
...
  [DisplayName("Country")]
  List<Country> Countries;

  Guid CountrySelected    <-- new field! 
...
}

I use Html.DropDownList("CountrySelected", Model.Countries.Select(x => new SelectItemList.. )

instead of HtmlDropDownListFor. HtmlDropDownListFor maps [id selected] to List not to CountrySelected property. Now [id selected] is mapped to CountrySelected

Andrew Florko