在客户端上格式化日期时间上发送表单提交默认的日期值 [英] formatting datetime on the clients sends default date value on form post

查看:100
本文介绍了在客户端上格式化日期时间上发送表单提交默认的日期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按照这个例子的正确适用日期时间格式

我有一个包含日期时间属性视图模式

 公共类MyViewModel {
    [DisplayFormat(ApplyFormatInEditMode = TRUE,DataFormatString ={0:DD.MM.YYYY HH:MM:SS})]
    公共DATETIME开始{搞定;组; }
}

里面查看我的形式

  @using(Html.BeginForm(NULL,NULL,NULL,FormMethod.Post,新{@id =myForm会,@name =myForm会}))
{
    ...
< D​​IV CLASS =表单组>
   @ Html.LabelFor(型号=> model.Starting,htmlAttributes:新{@class =控制标签COL-MD-2})
     < D​​IV CLASS =COL-MD-10>
       @ Html.EditorFor(型号=> model.Starting,新{htmlAttributes = {新@class =dateTimePicker的}})
       @ Html.ValidationMessageFor(型号=> model.Starting,新{@class =TEXT-危险})
     < / DIV>
< / DIV>
}

和在同一个页面内脚本的一节

 <脚本>
       jQuery.validator.addMethod(MyDateTimeFormat功能(价值元素){
            返回Date.parseExact(价值DD.MM.YYYY HH:MM:SS);
        },请提供正确的日期时间格式!);        变种形式= $(#myForm会);
        form.validate({
            规则:{
                开始:{MyDateTimeFormat:真正}
            }
        });
        $(#myForm会)。递交(函数(){
            如果(form.valid())
               警报(形式是有效的:\\ n+ Date.parse($(#正在启动)VAL()));
                $(#正在启动)VAL()= Date.parse($(#正在启动)VAL()。)。
            其他{
                警报(有效+ form.valid());
            }
        });
    < / SCRIPT>

日期格式正确应用,但里面的控制器我得到的 HttpPost 行动提交表格后, MyViewModel.Starting 用默认值 01/01/0001 不是这在视图中选择一个。我做错了吗?

编辑:
加入的Global.asax.cs

 保护无效的Application_BeginRequest(对象发件人,EventArgs的发送)
{
    字符串cultureName = CultureHelper.GetImplementedCulture(去-DE);
    Thread.CurrentThread.CurrentCulture =新的CultureInfo(cultureName);
    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}


解决方案

.NET是根据当前区域性集分析日期(和数字)。 ASP.NET中的文化不依赖于浏览器文化,但在文化ASP.NET线程运行。所以,如果你想传递的日期以特定的格式有(至少)两个选项:


  1. 设置当前线程的培养(或至少日期格式)到一个特定的值。例如(这应该与你的例子):

     保护无效的Application_BeginRequest(对象发件人,EventArgs的发送)
    {
        字符串cultureName = CultureHelper.GetImplementedCulture(去-DE);
        Thread.CurrentThread.CurrentCulture =新的CultureInfo(cultureName);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }

    请找到 CultureHelper 来自的这里不要忘记添加支持的语言(见列表 _cultures )。


  2. 创建按照您的需要过滤的DateTime 领域模型粘合剂。一个例子可以在这里找到


修改:更新例如

I'm trying to follow this example to correctly apply datetime format

I have view model which contains datetime property

public class MyViewModel {
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy HH:mm:ss}")]
    public DateTime Starting { get; set; }
}

inside view I have form

@using (Html.BeginForm(null, null, null, FormMethod.Post, new { @id = "myForm", @name = "myForm" }))
{
    ...   
<div class="form-group">
   @Html.LabelFor(model => model.Starting, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
       @Html.EditorFor(model => model.Starting, new { htmlAttributes = new { @class = "dateTimePicker" } })
       @Html.ValidationMessageFor(model => model.Starting, "", new { @class = "text-danger" })
     </div>
</div>
}

and on the same page inside scripts section

    <script>
       jQuery.validator.addMethod("MyDateTimeFormat", function (value, element) {
            return Date.parseExact(value, "dd.MM.yyyy HH:mm:ss");    
        }, "Please provide correct datetime format!");

        var form = $("#myForm");
        form.validate({
            rules: {
                Starting: { MyDateTimeFormat: true }
            }
        });
        $("#myForm").submit(function () {            
            if (form.valid())
               alert("The form is valid: \n" + Date.parse($("#Starting").val()));
                $("#Starting").val() = Date.parse($("#Starting").val());
            else {
                alert("Valid: " + form.valid());
            }
        });
    </script>

Date format is correctly applied but after submitting form on the HttpPost action inside controller I'm getting MyViewModel.Starting with default value 01/01/0001 not the one which is selected at the view. What I'm doing wrong?

Edit: Added into Global.asax.cs

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string cultureName = CultureHelper.GetImplementedCulture("de-DE");
    Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}

解决方案

.NET is parsing dates (and numbers) according to the current culture set. The culture in ASP.NET depends not on the browsers culture but on the culture the ASP.NET thread is running. So if you want to pass dates in a specific format there are (at least) two options:

  1. Set the current thread's culture (or at least the date format) to a specific value. For example (this should match your example):

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string cultureName = CultureHelper.GetImplementedCulture("de-DE"); 
        Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }
    

    please find CultureHelper from here and do not forget to add your supported languages (see list _cultures).

  2. Create a model binder that filters DateTime fields according to your needs. An example can be found here.

EDIT: Updated example

这篇关于在客户端上格式化日期时间上发送表单提交默认的日期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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