I have defined the following select list:
<%= this.Select("Scope")
.Options(Scopes.AllValues) // static property to get all possible values
.FirstOption("Select scope")
.Class("required")
.Selected(Model.Scope) %>
where Scope is an enum defined like this:
public enum Scope
{
Full,
Partial
}
I’m using this on a user control which renders all the form elements for a create/edit form, so I want this to work both when there is an underlying model and when the model is just an empty editmodel with no properties set. However, as Scope is a struct, it is initialized to the default value (which is the first defined enum value, Full) when the edit model is instantiated. Thus, the Select value option is never selected.
I know that Model.ID == 0 for new objects, and that Model.ID != 0 for existing objects, so I could use that to determine what should be shown. However, if I do
.Selected(Model.ID != 0 ? Model.Scope : null) // how do I indicate the first item?
I get a compiler error because there is no conversion between null and Scope (since Scope is a struct).
How should I accomplish this?
I solved this: Using the overload
.FirstOption(string value, string text)I could assign a value to the first option, and then use that as the fallback if the scope wasn’t set.