MVC3 Validation with ComponentModel.DataAnnotations for UK date format (also using jquery ui datepicker)

前端 未结 6 873
后悔当初
后悔当初 2021-01-05 14:25

I see there are some similar questions to this, but none solve my issue.

I am working on an MVC3 app with Entity Framework 4.3. I have a UK date field that i plan t

6条回答
  •  生来不讨喜
    2021-01-05 15:01

    You have to write you own ModelBinder for the DateTime type.

    This is a binder that I wrote for a similar problme but with Decimal type (maybe you will need it). you should grasp the idea and adapt it to your need

    public class DecimalModelBinder : IModelBinder
    {
      public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      {
        ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
          actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
          modelState.Errors.Add(e);
        }
    
        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
      }
    }
    

    Then in global.asax you register your binder and you're done

    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      RegisterGlobalFilters(GlobalFilters.Filters);
      RegisterRoutes(RouteTable.Routes);
      //Here you tell how to hendle the specific type 
      ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    }
    

    UPDATE

    After your clarification this answer should help

提交回复
热议问题