我的客户想要一个必须包含以下项目的表格:
- 姓名
- 电子邮件
- 地址
- 状态
在此应用程序的管理面板上,他想设置管理面板上表单项的顺序。 解决这个问题的最佳方法是什么?我想为每个字段保持正确的验证。
我在想一个包含表单项顺序的数组,但我不知道如何按该顺序显示表单项。
需要在数据库中设置排序顺序。
非常感谢帮助
最佳答案
首先您必须创建一个数据库表,TextBoxes
来保存设置(也可以从管理面板修改),包含以下列:
CREATE TABLE TextBoxes
(
Id int NOT NULL PRIMARY KEY,
Ordinal int NOT NULL,
TextBoxName nvarchar(255) NOT NULL
);
通过使用 TextBoxName
值向其中添加一些记录,例如 name
、address
、state
等 - 这稍后将用于映射 UI 控件 - 以及 Ordinal
列中的所需顺序。将表格添加到您的模型。
创建以下类(我假设包含问题中属性的实体名为 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
模型中添加另一个属性来保存多个模型的属性顺序,您可以扩展通过一些额外的过滤将逻辑应用到您的其他模型。
关于c# - 如何按从数据库中检索到的特定顺序显示表单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872251/