Advertisement
Guest User

Untitled

a guest
Nov 27th, 2014
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. public abstract class QuestionAnswerInputModel {
  2. public Guid QuestionId {
  3. get; set;
  4. }
  5. }
  6.  
  7. public class RatingQuestionInputModel : QuestionAnswerInputModel{
  8. [Required]
  9. [Range(1,4)]
  10. public int? Rating { get; set; }
  11. }
  12.  
  13. public class FreeTextQuestionInputModel: QuestionAnswerInputModel{
  14. [Required]
  15. public string FreeText { get; set; }
  16. }
  17.  
  18. public class QuestionAnswerModelBinder : DefaultModelBinder {
  19. public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
  20.  
  21. QuestionAnswerInputModel model;
  22.  
  23. if ((typeof(QuestionAnswerInputModel) != bindingContext.ModelType)) {
  24. return null;
  25. }
  26.  
  27. ModelBindingContext context = new ModelBindingContext(bindingContext);
  28.  
  29. Type typeOfModel;
  30.  
  31. string prefix = bindingContext.ModelName;
  32. if (bindingContext.ValueProvider.ContainsPrefix(prefix + "." + new FreeTextQuestionInputModel().GetPropertyName(m => m.FreeText))) {
  33. typeOfModel = typeof(FreeTextQuestionInputModel);
  34. } else if (bindingContext.ValueProvider.ContainsPrefix(prefix + "." + new RatingQuestionInputModel().GetPropertyName(m => m.Rating))) {
  35. typeOfModel = typeof(RatingQuestionInputModel);
  36. } else {
  37. return null;
  38. }
  39.  
  40. context.ModelMetadata = new ModelMetadata(new DataAnnotationsModelMetadataProvider(), bindingContext.ModelMetadata.ContainerType, null, typeOfModel, bindingContext.ModelName);
  41. return base.BindModel(controllerContext, context);
  42. }
  43. }
  44.  
  45. new DefaultModelBinder().BindModel(controllerContext, context)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement