.net Razor 在视图中将枚举转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13396424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:42:40  来源:igfitidea点击:

Razor converting enum to int inside a view

.netasp.net-mvcasp.net-mvc-4razor

提问by Kuttan Sujith

I a razor view .I have line like bleow

I a razor view .I have line like bleow

<option value='@{(Int16)PhoneType.Work}'>@PhoneType.Work</option>

This is an option in a select list/dropdownlist In this I have an enum PhoneType. For text filed @PhoneType.Work works fine but for value field @{(Int16)PhoneType.Work is not working

这是选择列表/下拉列表中的一个选项 在此我有一个枚举 PhoneType。对于文本归档 @PhoneType.Work 工作正常,但对于值字段 @{(Int16)PhoneType.Work 不起作用

What can i do to get integer value of the enum at value field

我该怎么做才能在 value 字段中获取枚举的整数值

回答by Stéphane Bebrone

This syntax should do the trick (note the () instead of {}):

这种语法应该可以解决问题(注意 () 而不是 {}):

<option value='@( (Int16) PhoneType.Work )'>@PhoneType.Work</option>

回答by dove

Why not have another field on your viewModel that is an integer

为什么不在您的 viewModel 上有另一个整数字段

public WorkId {get {return (int)Work; }

and use this in your view

并在您看来使用它

<option value='@PhoneType.WorkId'>@PhoneType.Work</option>

回答by vineel

We can use ChangeType function as below. Hope this helps for someone in future.

我们可以使用 ChangeType 函数,如下所示。希望这对将来的某人有所帮助。

<option [email protected](PhoneType.Work, PhoneType.Work.GetTypeCode())>@PhoneType.Work</option>

or

或者

<option [email protected](PhoneType.Work, typeof(int))>@PhoneType.Work</option>