ASP .NET MVC - 使用枚举作为模型的一部分 [英] ASP .NET MVC - Using a enum as part of the model

查看:22
本文介绍了ASP .NET MVC - 使用枚举作为模型的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(刚学MVC)

我创建了一个模型类:

public class Employee
    {
        public int ID { get; set; }

        [Required(ErrorMessage="TM Number is Required")]
        public string tm_number { get; set; }

        //use enum?
        public tmRank tm_rank { get; set; }
    }

模型类引用枚举'tmRank':

The model class refers to the enum 'tmRank':

public enum tmRank
    {
        Hourly, Salary
    }

当我从这个模型创建一个视图时,'tm_rank' 字段没有出现?我希望 MVC 会创建一个枚举值列表.

When I create a view from this model the 'tm_rank' field does not appear? My hope was that MVC would create a list of the enum values.

推荐答案

我猜它不知道为 Enum 创建什么类型的字段.一个 Enum 可以绑定到一个下拉列表、一组单选按钮、一个文本框等.

My guess is it doesn't understand what type of field to create for an Enum. An Enum can be bound to a dropdown list, a set of radio buttons, a text box, etc.

您的 Enum 需要什么类型的条目?他们应该从列表中选择它吗?回答这个问题可以帮助我们处理这种情况所需的代码.

What type of entry do you want for your Enum? Should they select it from a list? Answering that can help us with the code needed for that situation.

编辑以根据您的评论添加代码:

Edited to add code per your comment:

public static SelectList GetRankSelectList()
{

    var enumValues = Enum.GetValues(typeof(TmRank)).Cast<TmRank>().Select(e => new { Value = e.ToString(), Text = e.ToString() }).ToList();

    return new SelectList(enumValues, "Value", "Text", "");
}

然后在您的模型中:

public class Employee
{
    public Employee() 
    { 
        TmRankList = GetRankSelectList();
    }

    public SelectList TmRankList { get; set; }
    public TmRank TmRank { get; set; }
}

最后你可以在你的视图中使用它:

And finally you can use it in your View with:

<%= Html.DropDownListFor(c => c.TmRank, Model.TmRankList) %>

这将保存 TmRankList 中的枚举值.当您的表单发布后,TmRank 将保留所选值.

This will hold the enum values in TmRankList. When your form is posted, TmRank will hold the selected value.

虽然我在没有visual studio的情况下写了这个,所以可能会有问题.但这是我用来解决它的一般方法.

I wrote this without visual studio though, so there might be issues. But this is the general approach that I use to solve it.

这篇关于ASP .NET MVC - 使用枚举作为模型的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆