我需要在表单上显示一组问题,可能有一个问题或多个问题,问题的答案可能有不同的类型(例如,年龄、姓名、出生日期等) .
到目前为止,我设法想出的是一个 View 模型:
public class QuestionViewModel
{
public List<QuestionType> Questions { get; set; }
}
它显示一个类型为 QuestionType 的列表:
public class QuestionType
{
public int QuestionID { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
}
我需要知道的是,是否可以在属性上指定一些允许我更改类型的内容?我觉得这是不可能的,所以如果失败了,是否有任何关于我如何处理这个问题的建议,让它尽可能与 MVC 保持一致?
我想这样做的原因是它连接到默认的 MVC 框架验证并将其验证为正确的类型,例如将“Hello”写入要求“年龄”的问题中。
如果无法将类型信息存储在模型中,我有一个解决方法:
public class QuestionType
{
public int QuestionID { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
public string TypeInfo { get; set; }
}
并使用存储在那里的信息来编写自定义验证逻辑。
最佳答案
将您的 Answer 属性更改为一个对象:
public class QuestionType
{
public int QuestionID { get; set; }
public string Question { get; set; }
public object Answer { get; set; }
}
使用对象:
public void HandleAnswer(QuestionType qt)
{
if (qt.Answer is Boolean)
{
//do boolean stuff
}
else if (qt.Answer is String)
{
//do string stuff
}
else if (qt.Answer is Int32)
{
//do int stuff
}
//do unknown object stuff
}
关于c# - 更改模型 MVC 上的属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26634462/