在Shamsi日历中仅显示日期

时间:2015-07-14 12:37:48

标签: c# asp.net-mvc

我使用此代码显示Persian date

这是我的模特:

public class PaperOrder
{

    public int PaperOrderId { get; set; }

    [DisplayName("سفارش دهنده")]
    public string CustomerName { get; set; }

    [DisplayName("گیرنده")]
    public string ReceiverName { get; set; }

    [DisplayName("شماره تماس")]
    public string Tel { get; set; }


    [DisplayName(" نوع سفارش")]
    public String OrderType { get; set; }


    [DisplayName("تعداد")]
    public String Count { get; set; }

    [DisplayName("وضعیت سفارش")]
    public OrderStatus OrderStatus { get; set; }

    [DisplayName("تاریخ ارسال سفارش")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? StartDate { get; set; }

    [DisplayName("تاریخ اتمام سفارش")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? CompleteDate { get; set; }
}

和其他课程:

   public class PersianCulture : CultureInfo
    {
        private readonly System.Globalization.Calendar cal;
        private readonly System.Globalization.Calendar[] optionals;

        public PersianCulture()
            : this("fa-IR", true)
        { }

        public PersianCulture(string cultureName, bool useUserOverride)
            : base(cultureName, useUserOverride)
        {
            cal = base.OptionalCalendars[0];
            var optionalCalendars = new List<System.Globalization.Calendar>();
            optionalCalendars.AddRange(base.OptionalCalendars);
            optionalCalendars.Insert(0, new PersianCalendar());
            Type formatType = typeof(DateTimeFormatInfo);
            Type calendarType = typeof(System.Globalization.Calendar);
            PropertyInfo idProperty = calendarType.GetProperty("ID", BindingFlags.Instance | BindingFlags.NonPublic);
            FieldInfo optionalCalendarfield = formatType.GetField("optionalCalendars", BindingFlags.Instance | BindingFlags.NonPublic);
            var newOptionalCalendarIDs = new Int32[optionalCalendars.Count];

            for (int i = 0; i < newOptionalCalendarIDs.Length; i++)
                newOptionalCalendarIDs[i] = (Int32)idProperty.GetValue(optionalCalendars[i], null);

            optionalCalendarfield.SetValue(DateTimeFormat, newOptionalCalendarIDs);

            optionals = optionalCalendars.ToArray();

            cal = optionals[0];

            DateTimeFormat.Calendar = optionals[0];

            DateTimeFormat.MonthNames = new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند", "" };
            DateTimeFormat.MonthGenitiveNames = new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند", "" };
            DateTimeFormat.AbbreviatedMonthNames = new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند", "" };
            DateTimeFormat.AbbreviatedMonthGenitiveNames = new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند", "" };
            DateTimeFormat.AbbreviatedDayNames = new string[] { "ی", "د", "س", "چ", "پ", "ج", "ش" };
            DateTimeFormat.ShortestDayNames = new string[] { "ی", "د", "س", "چ", "پ", "ج", "ش" };
            DateTimeFormat.DayNames = new string[] { "یکشنبه", "دوشنبه", "ﺳﻪشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه" };
            DateTimeFormat.AMDesignator = "ق.ظ";
            DateTimeFormat.PMDesignator = "ب.ظ";
            DateTimeFormat.ShortDatePattern = "yyyy/MM/dd";
            DateTimeFormat.ShortTimePattern = "HH:mm";
            DateTimeFormat.LongTimePattern = "HH:mm:ss";
            DateTimeFormat.FullDateTimePattern = "yyyy/MM/dd HH:mm:ss";


        }

        public override System.Globalization.Calendar Calendar
        {
            get { return cal; }
        }

        public override System.Globalization.Calendar[] OptionalCalendars
        {
            get { return optionals; }
        }

        public static DateTime PersianToGregorianUS(DateTime faDate)
        {
            return new PersianCalendar().ToDateTime(faDate.Year, faDate.Month, faDate.Day, faDate.Hour, faDate.Minute, faDate.Second, faDate.Millisecond);
        }

    }

public class DateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        var date = (DateTime)value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
         date = PersianCulture.PersianToGregorianUS(date);

        return date;
    }
}

public class NullableDateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null)
        {
            var date = (DateTime)value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
            if (date!= null)
                date = PersianCulture.PersianToGregorianUS(date);

            return date;
        }
        return null;
    }
}
    public class DateTimeActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            //if (System.Threading.Thread.CurrentThread.CurrentCulture.LCID == 1065)
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = new PersianCulture();
        }
    }

的global.asax

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalFilters.Filters.Add(new DateTimeActionFilter());
            ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
          ModelBinders.Binders.Add(typeof(DateTime?), new NullableDateTimeBinder());
}

我的edit.cshtml

的一部分
  <div class="form-group">
        @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.StartDate, new { @id = "pcal1", @class = "pdate form-control" })
            @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CompleteDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.CompleteDate, new { @id = "pcal2", @class = "pdate form-control" })
            @Html.ValidationMessageFor(model => model.CompleteDate, "", new { @class = "text-danger" })
        </div>
    </div>

每件事情都很好,但是当我想在我的应用程序中只显示日期时,它并没有正确显示。
例如,当我想在输入中只显示日期时,它会像这样显示它(看零):enter image description here

1 个答案:

答案 0 :(得分:1)

在视图中替换代码:

@Html.TextBoxFor(model => model.StartDate, new { @id = "pcal1", @class = "pdate form-control" })

以下内容:

@Html.TextBox("StartDate", Model.StartDate.Value.ToShortDateString(), new { @id = "pcal1", @class = "pdate form-control" })

如果没有指定将DateTime值转换为String的特定方法,则会调用方法ToString()来显示时间部分。为避免这种情况,您必须在此情况下指定ToShortDateString()的正确方法。不要忘记检查可能的空引用。