MVC 5 DataAnnotation 订单属性

MVC 5 DataAnnotation Order Attribute

我无法使显示 -> 订单属性起作用。

我正在使用 VS2013 更新 4,System.ComponentModel.DataAnnotations 似乎是最新的运行时版本 4.0.30319。

我用一个小模型构建了一个微型 MVC 应用程序:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace TestDataAnnotation.Models
{
    [MetadataType(typeof(TestDB))]

    public class TestDB
    {
        public int TestDBID { get; set; }

        [Display(Order=2)]
        public int MyProperty1 { get; set; }
        [Display(Order=1)]
        public int MyProperty2 { get; set; }
    }
}

我使用脚手架创建了一个控制器和视图。创建的 GET 是标准 MVC

        // GET: TestDBs/Create
        public ActionResult Create()
        {
            return View();
        }

View也是标准的MVC:

    <div class="form-horizontal">
        <h4>TestDB</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.MyProperty1, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MyProperty1, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MyProperty1, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.MyProperty2, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MyProperty2, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MyProperty2, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

MyProperty2 应该首先显示,但它没有。我已经尝试了很多变体,但无法使 "Order" 工作。我在代码中有 MetadataType 语句,但在代码中没有。我试过命令= -9。我为 order 属性尝试了各种不同的值。显示->名称工作正常。显然,我在这里遗漏了一些关键想法。感谢您提供的所有帮助!

Order 参数适用于对模型进行动态操作并生成 HTML 的情况,例如网格视图。在这里,您确实按照给定的顺序呈现了属性。设置 Order 不会覆盖显式 HTML.