Question

I'm using ASP.NET MVC and I have the follwoing model class:

public enum ListType
{
    black,
    white
}
public class ListAddSiteModel : ApiModel
{
    [RequestParameter]
    public ListType list { get; set; }
}

But it doesn't work the way I want. When I don't pass list parameter in the requested URL I have that list is black. But I want that if the list parameter is not black or white string then list must be null. Is it possible to write custom attribute [IsParsable] and just add it to the list property.

public class ListAddSiteModel : ApiModel
{
    [RequestParameter]
    [IsParsable]
    public ListType list { get; set; }
}
Was it helpful?

Solution 2

The only way you can pass a value that is not black or white, is to pass an int. You can prevent that by adding a check in your setter that calls Enum.IsDefined, eg:

ListType? _listType;
public ListType? List
{
    get
    { 
        return _listType;
    }
    set
    {
        //Enumb.IsDefined doesn't like nulls
        if (value==null || Enum.IsDefined(typeof(ListType),value))
            _listType=value;
        else
            _listType=null;
    }
}

You can also combine this with Henk Holterman's answer and add an NA member equal to 0 in your enumeration. This will probably make your code easier to read.

In both cases your code will have to take care of the special values (NA or null). Using a nullable type makes it harder to forget this, but does litter your code a bit.

OTHER TIPS

Easy way out:

public enum ListType
{
    novalue = 0, 
    black,
    white
}

the dummy must be first (map to 0 == default(Enum))

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