Changing property type on MVC model

I need to display a group of questions in a form, one question or many questions may arise, and the answers to questions may be of different types (for example, age, name, date of birth, etc.).

So far I've managed to find the view model:

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

      

Displays a list of QuestionType types:

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 in the property that will allow me to change the type? I have a feeling that this is not possible, so if it is not, are there any suggestions as to how I can handle this while keeping it as inline with MVC as possible?

The reason I want to do this is because it hooks into the default MVC structure validator and checks it for the correct type, for example "Hello" to a question that asks "Age".

I have an idea for a workaround if this is not possible when 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.

+3


source to share


1 answer


Change the Reply property to the object:

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

      



Use 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

}

      

+2


source







All Articles