更改模型MVC上的属性类型

时间:2021-04-24 17:04:24

I have the need to display a group of questions on a form, there could be one question or many questions, and the answers to the questions could be of different types (for instance, Age, Name, date of birth etc).

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

So far what I've managed to come up with is a View Model:

到目前为止,我想出的是一个视图模型:

public class QuestionViewModel
{
   public List<QuestionType> Questions { get; set; }
}

It displays a List of type QuestionType:

它显示一个类型为QuestionType的列表:

public class QuestionType
{
    public int QuestionID { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

What I need to know is, is it possible to specify something on the property that would allow me to change the type? I have the feeling it isn't possible, so failing that, are there any suggestions as to how I can deal with this, keeping it as inline with MVC as possible?

我需要知道的是,是否可以在属性上指定允许我更改类型的内容?我觉得这是不可能的,如果不行的话,我有什么建议来解决这个问题,让它尽可能地与MVC保持一致吗?

The reason I want to do this is so that it hooks up into the default MVC framework validation and will validate it to the correct type, as an example writing "Hello" into a question that is asking for "Age".

我这样做的原因是为了使它与默认的MVC框架验证相关联,并将其验证为正确的类型,如将“Hello”写入正在询问“Age”的问题的示例。

I have an idea for a workaround if it isn't possible where I store the type information in the model as such:

如果不可能在模型中存储类型信息,我有一个解决方案的想法:

public class QuestionType
{
    public int QuestionID { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
    public string TypeInfo { get; set; }
}

and using the information stored there to write custom validation logic.

并使用存储在那里的信息编写自定义验证逻辑。

1 个解决方案

#1


2  

Change your Answer property to an object:

将您的答案属性更改为一个对象:

public class QuestionType
{
    public int QuestionID { get; set; }
    public string Question { get; set; }
    public object Answer { get; set; }
}

Use the object:

使用对象:

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

}

#1


2  

Change your Answer property to an object:

将您的答案属性更改为一个对象:

public class QuestionType
{
    public int QuestionID { get; set; }
    public string Question { get; set; }
    public object Answer { get; set; }
}

Use the object:

使用对象:

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

}