0

Model

[Required]
 [Display(Name = "Source")]
  [Range(typeof(string), "0","10", ErrorMessage = "Please select Source")]
   public string Source { get; set; }

View

 @Html.DropDownListFor(model => model.Source, new SelectList(new[]
                                          {
                                           new {ID="select",Name="Select"},
                                            new{ID="Facebook",Name="Facebook"},  
                                              new{ID="Twitter",Name="Twitter"}, 
                                                new{ID="LinkedIn",Name="LinkedIn"}, 
                                                                                  },
                      "ID", "Name", 1), new { style = "height:24px;" })  

How can I validate this using data annotations? I need to store ID as text like Facebook in db.

Syed Farjad Zia Zaidi
  • 3,302
  • 4
  • 27
  • 50
Ram
  • 337
  • 5
  • 23

3 Answers3

0

You can use IValidatableObject interface and implement your own validation of your model class.

How do I use IValidatableObject?

Community
  • 1
  • 1
matt_lethargic
  • 2,706
  • 1
  • 18
  • 33
0
@Html.DropDownListFor(model => model.Source, new SelectList(new[]
                                          {

                                            new{ID="Facebook",Name="Facebook"},  
                                              new{ID="Twitter",Name="Twitter"}, 
                                                new{ID="LinkedIn",Name="LinkedIn"}, 
                                                                                  },
                      "ID", "Name", 1),"Select", new { style = "height:24px;" })  

I have given like this. Its working fine now.

Ram
  • 337
  • 5
  • 23
0

You have already decorated your model with data annotations. Now you only need to put unobtrusive jquery scripts to enable your validations on client side. Server side validation should work as is. I fail to understand the rationale of Range Attribute on select list though.

Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155