如何将 int 选项键转换为视图中的字符串值 asp.net mvc c#
我有一个在其上呈现一些下拉菜单的视图。它们是根据 IDictionary 构建的。
当我渲染视图并且想要显示这些选项之一的当前选定值时,我想了解如何将视图中的数字转换为字典中的字符串值。
我对此已经很了解了(因为我的字典从 0 开始),但它不太有效。
<%= Html.Encode(Chart.TypeDictionary.ElementAt(Model.iType)) %>
这返回这个
[Public, 0]
大概我只能得到左边的值?
有没有人对此有更好的解决方案,以及当您没有下拉菜单时最好的方法是什么。
我以前使用过枚举,但显然其中不能有空格。
I have a view that renders a few drop downs on it. These are built from IDictionary's.
When I render a view and I want to show the currently selected value of one of these options, I want to see how to convert the number in my view into the string value in the dictionary.
I got quite far with this (as my dictionary starts from 0) but it doesn't quite work.
<%= Html.Encode(Chart.TypeDictionary.ElementAt(Model.iType)) %>
this returns this
[Public, 0]
Presumably I can just get the value on the left?
Does anyone have a better solution to this, and also what is the best way to do it when you don't have drop downs.
I have used enums before, but obviously you can't have spaces in them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不行吗?
编辑
如果没有更多背景信息,我无法就我认为解决此问题的最佳方法向您提供明确的答案。当我显示下拉列表时,我通常会以一种可以轻松创建下拉列表的形式将选项存储在视图模型中。例如:
但是,如果您使用相同的模型作为控制器操作的输入值,则这将不起作用。在这种情况下,我会将选项存储在 ViewData 中。如果您表示枚举值类型,一种选择是创建一个扩展方法,该方法接受相关枚举类型以及当前值,并为您创建一个下拉列表。如果您在枚举值中遵循 CamelCase 约定,则可以简单地让此方法在小写字母和大写字母之间放置一个空格。 (例如CamelCase =>“Camel Case”)。
Does this not work?
Edit
Without more context, I can't give you a definitive answer on what I'd consider to be the best way to go about this. When I'm displaying a dropdown list, I'll often store the options in the view model in a form that will make it easy to create the dropdown. For example:
However, if you're using the same model as an input value to your controller action, this won't work. In that case, I'd store the options in the ViewData. If you're representing an enum value type, one option is to create an extension method that takes the enum type in question, along with the current value, and creates a dropdown list for you. If you follow the CamelCase convention in your enum values, you can simply have this method put a space between lower-case and upper-case letters. (e.g. CamelCase => "Camel Case").