MvcContrib.FluentHtml 选择列表的默认选定值
我定义了以下选择列表:
<%= this.Select("Scope")
.Options(Scopes.AllValues) // static property to get all possible values
.FirstOption("Select scope")
.Class("required")
.Selected(Model.Scope) %>
其中 Scope
是一个如下定义的枚举:
public enum Scope
{
Full,
Partial
}
我在用户控件上使用它,该控件呈现创建/编辑表单的所有表单元素,所以我想要这个当存在基础模型和模型只是一个没有设置属性的空编辑模型时都可以工作。但是,由于 Scope
是一个结构体,因此在实例化编辑模型时,它会被初始化为默认值(即第一个定义的枚举值 Full
)。因此,永远不会选择选择值
选项。
我知道 Model.ID == 0
对于新对象,Model.ID != 0
对于现有对象,所以我可以用它来确定应该显示什么。但是,如果这样做,
.Selected(Model.ID != 0 ? Model.Scope : null) // how do I indicate the first item?
我会收到编译器错误,因为 null
和 Scope
之间没有转换(因为 Scope
是一个结构)。
我应该如何实现这个目标?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我解决了这个问题:使用重载
.FirstOption(string value, string text)
我可以为第一个选项分配一个值,然后在未设置范围时将其用作后备。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.