1

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; }
}
2
  • 3
    list cannot be null as an enum is not a nullable type. You should define it as public ListType? list or else give ListType a default value (ListType.none) - also you should capitalize those enum and property names Commented May 7, 2014 at 7:15
  • @RGraham What does question mark mean? Commented May 7, 2014 at 7:24

2 Answers 2

4

Easy way out:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Still won't prevent someone from passing an invalid value, if that was the actual question
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.

4 Comments

What does question mark in the ListType? _listType; mean. This contruction is ungooglable.
This is the C# syntax for a nullable type. It's used to allow handling of nulls for value types that would otherwise not allow null values. It's in C# since .NET 2.0, so it's practically everywhere.
Is the explicit property declaration required here? Won't MVC automatically bind a nullable enum to null if the provided value is not found within the type?
@RGraham This won't prevent user code from passing a bad value. If that's not a concern, you could just keep the nullable declaration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.