angularjs - 我如何使用 AngularJs 显示枚举值

标签 angularjs asp.net-web-api enums

我已经在我的模式中创建了一个枚举。

public enum Color
{
    Green,
    Black,
    Red,
    Silver,
    Yellow,
    White,
    Grey,
}

我在我的主类中使用了 thus 枚举。

public class MotorDetails
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string Make { get; set; }
    public string Model { get; set; }
    public string Year { get; set; }
    public string Kilometers { get; set; }
    public Color Color { get; set; }
 }

然后我像这样播种数据

context.MotorDetails.AddOrUpdate(x => x.Id, new MotorDetails()
{
   Name = "Accord",
   Make = "Honda",
   Model = "Accord",
   Year = r.Next(1980,2016).ToString(),
   Kilometers = r.Next(50000, 200000).ToString(),
   Color = (Color)r.Next(1,7),
}

因此,在数据库中,任何值 b/w 1,7 都被保存为颜色。 哪个好。

现在我将这些数据从 Controller 返回到我的 View

public List<MotorDetails> getByMake(string make, int minPrice, int maxPrice)
{
    List<MotorDetails> motor = db.MotorDetails.Where(x => x.Make == make && x.Price >= minPrice && x.Price <= maxPrice).ToList();
    return motor;
}

问题: 它向我的 View 返回一个颜色整数,因此数字显示在 View 上。 我想显示给定数字的颜色名称。

我正在使用 angularJs,这是我的代码。

<div>
<table class="table">
    <tr>
        <th>Name</th>
        <th>Make</th>
        <th>Model</th>
        <th>Year</th>
        <th>Kilometers</th> 
        <th>Price</th>   
        <th>Color</th>           
    </tr>
    <tr ng-repeat="m in motors">
        <td>{{m.Name}}</td>
        <td>{{m.Make}}</td>
        <td>{{m.Model}}</td>
        <td>{{m.Year}}</td>
        <td>{{m.Kilometers}}</td>
        <td>{{m.Price}}</td>
        <td>{{m.Color}}</td>
    </tr>
</table>
</div>

最佳答案

JSON.NET(ASP.NET 的默认 json 序列化程序)具有此 [JsonConverter(typeof(StringEnumConverter))] 的属性

所以

public class MotorDetails
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string Make { get; set; }
    public string Model { get; set; }
    public string Year { get; set; }
    public string Kilometers { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public Color Color { get; set; }
} 

将颜色序列化为字符串值。

关于angularjs - 我如何使用 AngularJs 显示枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33449250/

相关文章:

javascript - array.splice 在 Angular Js 指令中显示奇怪的行为

javascript - AngularJS - 无法访问 RootScope

ruby-on-rails - 如何在 Rails 3 的 Postgres 数据库中使用枚举?

php - MySQL:使用枚举的默认值创建表错误

angularjs - 将 `this` 传递给 ng-click 中的函数会暴露什么?

javascript - 对象分配在此 AngularJS Controller 中不起作用

c# - Ctrl+F5 在 VS 中的 ASP.NET 项目中如何工作?

c# - 使用 XMLHttpRequest 将带有参数的数据发送回 Web 服务器

c# - 如何读取包含 Datetime 类型的 BaseHttpActionResult 的响应

java - 在 Scala 中创建 Java 枚举