0

当涉及到不同的 UI 文化来显示日期时,我们都知道我们面临的问题。但是在发布时,我们也有这个问题,因为在发布时,ASP.NET MVC 并没有真正“自动”将给定的格式绑定到它认为合适的任何方式。

我的问题是,如何以 yyyy/MM/dd 格式回发日期,以便它可以正确绑定到模型属性?

我想以文化的 UI 格式显示日期格式(即英国/美国等),并让用户像往常一样从 jquery 日历中选择日期。但只有在发帖时,我才想做“更正”

这样做的最好方法是什么?

4

1 回答 1

1

我遇到了同样的问题,并通过为日期添加一个备用字段来解决它,我将其发送给控制器。

帮手:

public static CultureInfo UserCultureInfo()
{
    // Retrieves the user culture info based on the browser request
    var userLanguages = HttpContext.Current.Request.UserLanguages;

    CultureInfo ci;

    if (userLanguages.Length > 0)
    {
        try
        {
            ci = new CultureInfo(userLanguages[0]);
        }
        catch (CultureNotFoundException)
        {
            ci = CultureInfo.InvariantCulture;
        }
    }
    else
    {
        ci = CultureInfo.InvariantCulture;
     }

     return ci;
}

HTML(剃刀视图):

@{
    System.Globalization.CultureInfo curInfo = Helpers.UserCultureInfo();
}

<!-- You need to change the file to be loaded based on the Culture information returned above -->
@Html.Script("DatePicker/i18n/jquery.ui.datepicker-en-GB")

<!-- The hidden field should be the one posted back to the Controller -->
<input type="hidden" name="myDate" id="myDate" value="" />

<!-- This one is just to display the DatePicker -->
<input type="text" id="myDatePickerField" name="myDatePickerField" />

JS:

$("#myDatePickerField").datepicker({
    altField: "#myDate",
    altFormat: "yy-mm-dd", // The date sent will be in the YYYY-MM-DD format (refer to the HTML code to understand this bit)
    dateFormat: "dd/mm/yy" // As I'm in the UK, I set the default format to DD/MM/YYYY
});

这只是一个开始,一个关于如何实现预期结果的想法。当然,您需要实施更改以完成它并使其适合您的网站。如何检测用户区域设置信息并将其应用到您的解决方案有点更广泛和复杂。网上有很多技巧和教程。

于 2013-09-05T09:14:56.580 回答