如何使用自定义格式(dd.MM.yyyy)的jQuery UI DatePicker和MVC 4 [英] How to use jQuery UI DatePicker and MVC 4 with custom format (dd.MM.yyyy)

查看:118
本文介绍了如何使用自定义格式(dd.MM.yyyy)的jQuery UI DatePicker和MVC 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您要使用自定义罗马尼亚语格式的日期选择器:dd.MM.yyyy

Let's say you want to use the datepicker with the custom Romanian format: dd.MM.yyyy

如何做到这一点而又不会遇到jquery验证问题和回发后对日期时间的误解?

How can you do this without encountering jquery validation problems and misinterpreting of the date time after a postback ?

推荐答案

首先在jquery-ui.js之后包含datepicker-ro.js.

First of all include datepicker-ro.js after jquery-ui.js.

之后,按如下所示在模型中设置格式:

After that set the format in the model like this:

public class ProductionCalculationReportModel
    {
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? BeginDate { get; set; }

        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? EndDate { get; set; }        
    }

然后,在.cshtml文件中,您可以放置​​文本框:

Then, in .cshtml file you can put the textboxes:

@Html.TextBoxFor(x => x.BeginDate, "{0:dd.MM.yyyy}", new { @class = "datefield" })
@Html.TextBoxFor(x => x.EndDate, "{0:dd.MM.yyyy}", new { @class = "datefield" })

然后,也在cshtml文件中,让我们进行验证:

Then, also in the cshtml file, let's take care of the validation:

<script>
  $(function() {
      $("#BeginDate").datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 3,
      onClose: function( selectedDate ) {
          $("#EndDate").datepicker(
              {
                  minDate: selectedDate
                  , dateFormat: 'dd.mm.yy'
              }
              //"option", "minDate", selectedDate
              );
      }
    });
      $("#EndDate").datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 3,
      onClose: function( selectedDate ) {
          $("#BeginDate").datepicker(
              {
                  maxDate: selectedDate
                  , dateFormat: 'dd.mm.yy'
              }
              //"option", "maxDate", selectedDate
              );
      }
    });
  });

  $(function ()
  {
      $.validator.addMethod('date',
      function (value, element)
      {
          if (this.optional(element))
          {
              return true;
          }
          var ok = true;
          try
          {
              $.datepicker.parseDate('dd.mm.yy', value);
          }
          catch (err)
          {
              ok = false;
          }
          return ok;
      });          
  });

</script>

之后,创建一个模型活页夹:

After that create a model binder:

public class ProductionCalculationReportModelBinder : DefaultModelBinder
    {

        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            if (propertyDescriptor.ComponentType == typeof(PAS.Areas.Admin.Models.ProductionCalculationReportModel))
            {
                if (propertyDescriptor.Name == "BeginDate")
                {
                    var obj = bindingContext.ValueProvider.GetValue("BeginDate");
                    return DateTime.ParseExact(obj.AttemptedValue.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                }

                if (propertyDescriptor.Name == "EndDate")
                {
                    var obj = bindingContext.ValueProvider.GetValue("EndDate");
                    return DateTime.ParseExact(obj.AttemptedValue.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                }
            }
            return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
        }
    }

像这样在Global.asax中添加它:

Add it in Global.asax like this:

ModelBinders.Binders.Add(typeof(ProductionCalculationReportModel), new ProductionCalculationReportModelBinder()); 

然后像这样使用它:

[HttpPost]
        public ActionResult Index([ModelBinder(typeof(ProductionCalculationReportModelBinder))]ProductionCalculationReportModel model) {}

这篇关于如何使用自定义格式(dd.MM.yyyy)的jQuery UI DatePicker和MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆