C#MVC:DropDownList将枚举绑定到整型模型字段

编程入门 行业动态 更新时间:2024-10-11 11:14:46
本文介绍了C#MVC:DropDownList将枚举绑定到整型模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我如何将枚举绑定到类型为integer的模型字段?

我尝试了一些扩展方法,但是没有做好工作,导致所有方法需要将模型字段作为给定的枚举类型...

这是我的来源(模型和枚举):

型号:

public class Einheit { public Einheit() { Id = Guid.NewGuid(); } public Guid Id {get;组; } public short TypeOfSomething {get;组; } public long Verwendungszweck {get;组; }

枚举:

public enum Einheitsart { Type1 = 0, Type2 = 1, Type3 = 2, Type4 = 3 , Type5 = 4, Type6 = 5 }

我想要使​​值从0-6(为了能够保存Integer在我的模型),但是DropDownList应该显示文本Type1到Type6...

我的问题是将枚举转换为工作的SelectList。

谢谢!

解决方案

您可以枚举所有枚举值,并为每个枚举值创建SelectListItems。这应该工作:

var selectList = new List< SelectListItem>(); foreach(Einheitsart art in Enum.GetValues(typeof(Einheitsart))) { selectList.Add(new SelectListItem(){Value =(int)art,Text = art.ToString )})}

How can I bind an enum to a model-field of the type integer?

I tried some extension methods, but they didnt do a good job, cause all method required the model field to be the given enum-type...

Here is my source (Model and Enum):

Model:

public class Einheit { public Einheit() { Id = Guid.NewGuid(); } public Guid Id { get; set; } public short TypeOfSomething { get; set; } public long Verwendungszweck { get; set; } }

Enum:

public enum Einheitsart { Type1 = 0, Type2 = 1, Type3 = 2, Type4 = 3, Type5 = 4, Type6 = 5 }

I want to have the Values going from 0-6 (To be able to save the Integer in my Model), but the DropDownList should show the Text "Type1" to "Type6"...

The problem I have is converting the enum to a working SelectList.

Thank you!

解决方案

You can enumerate over all enum values and create SelectListItems for each of them. This should work:

var selectList = new List<SelectListItem>(); foreach(Einheitsart art in Enum.GetValues(typeof(Einheitsart))) { selectList.Add(new SelectListItem() { Value = (int)art, Text = art.ToString() }) }

更多推荐

C#MVC:DropDownList将枚举绑定到整型模型字段

本文发布于:2023-10-12 04:06:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   绑定   整型   模型   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!