0

Is it possible to create a data annotation that allows me to say if QuestionType = "dropdown" then SelectedValue is Required?

Here is my Model:

public class QuestionViewModel
{
    public int? Id { get; set; }

    public string QuestionType { get; set; }

    public string SubType { get; set; }

    public string Text { get; set; }

    public int SortOrder { get; set; }

    public bool IsHidden { get; set; }

    public int SelectedValue { get; set; }

    public List<QuestionOptionViewModel> Options { get; set; }
}

What I want to say is if the QuestionType is of a specific type (dropdown) then SelectedValue is Required.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
allencoded
  • 7,015
  • 17
  • 72
  • 126

2 Answers2

1

You can create a custom ValidationAttribute to do just about anything honestly.
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute(v=vs.110).aspx

Just inherit from ValidationAttribute and write the logic you need and toss the attribute on the property you want to conditionally validate. The standard CompareAttribute is very similar to this. http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.compareattribute(v=vs.110).aspx

Nick Nieslanik
  • 4,388
  • 23
  • 21
0

First of all I think that if your question type is a dropdown so the property should be integer.

After you did it, so you should use a Html.DropdownListFor to set validation for it.

public class QuestionViewModel
{
    public int? Id { get; set; }

    [Required(ErrorMessage="Required")]
    public int QuestionType { get; set; }

    public string SubType { get; set; }

    public string Text { get; set; }

    public int SortOrder { get; set; }

    public bool IsHidden { get; set; }

    public int SelectedValue { get; set; }

    public List<QuestionOptionViewModel> Options { get; set; }
}

And in your controller:

List<SelectListItem> typeList=new List<SelectListItem>();
foreach(var type in questionTypes)
{
    typeList.Add(new SelectListItem{Text=type.Name,Value=type.QuestionTypeId.ToString()});
}
ViewBag.QuestionTypes=typeList;

And in your view:

@Html.DropdownListFor(model=>model.QuestionType,ViewBag.QuestionTypes,"--Select One--")
@Html.ValidationMessageFor(model=>model.QuestionType)
Hamid Reza
  • 2,913
  • 9
  • 49
  • 76
  • Actually QuestionType is a string. They type will come from the db saying "dropdown". Then I will take a List of those Options out of the the public List Options. The selectedValue is actually a int? (I forgot to add the ?). And I am using DropDownListFor. – allencoded Feb 14 '14 at 19:41
  • So dont set any default values for your dropdown. This way always an option is selected. – Hamid Reza Feb 14 '14 at 19:51
  • Eh thats not the right way to handle this. Default value is the proper way and let them know if they forgot to use the dropdown. I have handled this now with the custom validation approach. – allencoded Feb 14 '14 at 20:05