c# - 更改模型 MVC 上的属性类型

标签 c# asp.net asp.net-mvc

我需要在表单上显示一组问题,可能有一个问题或多个问题,问题的答案可能有不同的类型(例如,年龄、姓名、出生日期等) .

到目前为止,我设法想出的是一个 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/

相关文章:

asp.net - 母版页使用母版页和继承

asp.net - IIS Express 错误 500.19 (0x80070003) 无法读取配置文件

asp.net - IIS 经典模式 .NET Web API 调用返回 404 错误

c# - System.IO.FileNotFoundException : Could not load assembly System. Web in Mono for Android

c# - 使用rest api将数据插入azure表存储时将odata类型插入json有效负载的最佳方法

c# - RelativeSource 绑定(bind)适用于 Style 但不适用于 ControlTemplate

c# - 加密 URL 中的路由数据

c# - 如何在我的新 CSPROJ 类库中包含带有 native dll 的 NuGet 包?

javascript - 从页面中删除行而不刷新页面

c# - 如何生成动态 C# 图像?