【发布时间】:2015-02-12 14:11:17
【问题描述】:
我正在尝试生成一个动态表单,其中包含来自数据库的问题。 每个问题都有其类型和其他属性。
我的课程示例:
public class QuestionnaireBase
{
public string Text { get; set; }
public int Sequence { get; set; }
}
public abstract class Question : QuestionnaireBase
{
public bool IsRequired { get; set; }
public bool WithComment { get; set; }
public abstract object Answer { get; set; }
}
public class TextQuestion : Question
{
public string DefaultText { get; set; }
public int MaxLength { get; set; }
public override object Answer { get; set; }
}
我想在答案字段中添加一些属性(DisplayAttribute、MaxLenght),这样当我使用 EditorFor 和 LabelFor 时,这些属性就会被考虑在内。
在检索我的问题时,我尝试在我的字段“答案”上添加一个属性(这里是一个存根):
Enumerable.Range(1, 5).Select(questionSeq => new TextQuestion {
Text = string.Format("Question {0}" questionSeq),
Answer = "TEXTVALUE" + questionSeq
}).Select(w => {
var skd = new DisplayAttribute();
skd.Name = w.Text;
TypeDescriptor.AddAttributes(w.Answer,skd );
return w;
})
现在,在我的视图中,我想使用 LabelFor 来显示这个 DisplayAttribute:
@Html.LabelFor(model => model.Questions[questionIndex].Answer)
这会将“答案”作为文本输出。 我可以通过这样做绕过这个问题:
@{
var attribute =
TypeDescriptor.GetAttributes(Model.Questions[questionIndex].Answer)[typeof(DisplayAttribute)];
var displayAttribute = ((DisplayAttribute) attribute);
}
@Html.LabelFor(model =>
model.Questions[questionIndex].Answer, displayAttribute.Name)
我的第一个猜测是,LabelFor 会在我的类型上使用 DisplayAttribute,而不是在我的实例上。
显然,我不想为每个属性都做这项工作,否则在运行时创建属性完全没用。
我可以做些什么来解决这个问题? 我想对 MaxLenghtAttribute/Range 做同样的事情。 感谢您的宝贵时间
【问题讨论】:
标签: c# razor model-view-controller data-annotations custom-attributes