3

我的客户想要一个必须包含以下项目的表单:

  • 姓名
  • 电子邮件
  • 地址
  • 状态

在此应用程序的管理面板上,他想在管理面板上设置表单项的顺序。解决这个问题的最佳方法是什么?我想为每个字段保持正确的验证。

我正在考虑一个包含表单项顺序的数组,但我不知道如何按该顺序显示表单项。

排序顺序需要在数据库中设置。

我会很感激帮助

4

2 回答 2

1

首先,您必须创建一个数据库表,TextBoxes以保存设置(也将在管理面板中进行修改),其中包含以下列:

CREATE TABLE TextBoxes
(
    Id int NOT NULL PRIMARY KEY,
    Ordinal int NOT NULL,
    TextBoxName nvarchar(255) NOT NULL
);

使用,TextBoxName等值向其中添加一些记录- 这稍后将用于映射 UI 控件 - 以及列中所需的顺序。将表格添加到您的模型中。nameaddressstateOrdinal

创建以下类(我假设包含问题中属性的实体名为Contact):

public class MyDataAnnotationsModelMetadataProvider : 
    System.Web.Mvc.DataAnnotationsModelMetadataProvider
{
    protected override System.Web.Mvc.ModelMetadata 
        CreateMetadata(IEnumerable<Attribute> attributes, 
            Type containerType, 
            Func<object> modelAccessor, 
            Type modelType, 
            string propertyName)
    {
        if (containerType == typeof(Contact))
        {
            // get the repository instance  
            var db = new MyModelEntities();
            // find the current textbox by it's property name
            var textBox = db.TextBoxes
                .FirstOrDefault(t => t.TextBoxName == propertyName);
            if (!string.IsNullOrWhiteSpace(propertyName) && textBox != null)
                attributes = attributes.Union(new List<Attribute>() {
                    new DisplayAttribute() { Order = textBox.Ordinal } 
                });
        }
        return base.CreateMetadata(attributes, 
            containerType, 
            modelAccessor, 
            modelType, 
            propertyName);
    }
}

Global.asax.cs文件中,修改Application_Start方法:

protected void Application_Start()
{
    // set the current metadata provider to our custom class
    ModelMetadataProviders.Current = new MyDataAnnotationsModelMetadataProvider();
    // other method content
    AreaRegistration.RegisterAllAreas();
    // etc
}

注意: 上面的示例将允许您动态更改一个模型的文本框的顺序,但是如果您在TextBoxes模型中添加另一个属性来保存多个模型的属性顺序,您可以将逻辑扩展到您的其他模型通过一些额外的过滤。

于 2013-06-01T14:57:54.200 回答
1

一种选择是在客户端订购它们。

完成此操作的步骤:

  • 在某种程度上,您必须将每个表单字段与相应的订单号相关联。
  • 以您可以识别每个字段的顺序的方式形成 HTML。
  • 实现 javascript 逻辑来处理 HTML 并以正确的顺序显示字段。

一个例子:

假设每个表单字段都位于一个具有通用标识符和订单号的 div 上:

<div id="official_div">
</div>
<div style="display:none">
    <div id="form_field_2">
       <--! Name Field here -->
    </div>
    <div id="form_field_1">
       <--! Email Field here -->
    </div>
    <div id="form_field_3">
      <--! Address Field here -->
    </div>
</div>

现在,知道了字段的数量,您可以实现一些 javascript 逻辑来将这些字段按正确的顺序放在一起,并将它们放在实际的表单字段官方 div 上:

  var officialDiv = document.getElementById('official_div');
  for(var i =1; i <= numberOfFields; i++)
  {
       var element  = document.getElementById('form_field_' + i);
       //include element inside officialDiv 
  }
于 2013-06-01T12:38:26.187 回答