ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c#-是否在ASP.Net Webforms中自动应用文化? (不是UICulture)

2019-10-28 00:08:00  阅读:251  来源: 互联网

标签:date-formatting webforms asp-net c


我有一个Webforms ASP.Net 4.5应用程序,该应用程序没有在web.config或代码中的其他位置指定文化或uiculture设置.我担心日期格式是否适合来自不同国家/地区的用户使用,即文化设置而非UICulture设置.

问题:如果来自英国,德国和美国的用户使用此ASP.Net应用程序,那么在asp:Label控件中显示日期值时会自动将其格式化吗?还是开发人员需要明确地进行这种格式化?

Label控件使用ASP.Net Webforms的数据绑定语法进行数据绑定,如下面的代码段所示.例如,如果对于美国用户而言,订购日期为10/4/2014,那么对于英国或德国用户而言,则应显示为4/10/2014.

HTML

<asp:Label id="lblOrderDate" runat="server" Text="<%# this.OrderDate %>"></asp:Label>

后台代码

protected void Page_Load(object sender,   EventArgs e)
{ 
   string orderId = this.txtOrderId.Text;
   Order order = DAL.GetOrder( orderId );
   this.OrderDate = order.OrderDate;
   this.Page.DataBind();
}

public DateTime OrderDate { get;set; }

更新1

我不确定是否需要在页面代码后面包含以下代码来设置区域性,还是由ASP.Net自动完成?我的猜测是ASP.Net会自动执行此操作,但不确定.

protected override void InitializeCulture()
{
    string language = "en-us";

    //Detect User's Language.
    if (Request.UserLanguages != null)
    {
        //Set the Language.
        language = Request.UserLanguages[0];
    }

    //Set the Culture.
    Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}

解决方法:

可以通过Asp.net根据浏览器的提示自动设置文化. (这是我们在Request.UserLanguages中得到的).如果您这样做,则为“<%#this.OrderDate%>”会根据此信息自动格式化.

Look at the documentation

To have ASP.NET set the UI culture and culture to the first language
that is specified in the current browser settings, set UICulture and
Culture to auto. Alternatively, you can set this value to
auto:culture_info_name, where culture_info_name is a culture name. For
a list of culture names, see CultureInfo. You can make this setting
either in the @ Page directive or Web.config file.

<%@ Page Culture="auto" %>

或全局所有页面.

<configuration>
   <system.web>
      <globalization culture="auto"/>
   </system.web>
</configuration>

但是您不能信任Request.UserLanguages.这只是浏览器的首选项.最好允许用户通过列表框进行选择.

您可以通过重写页面的initializeculture调用,以编程方式为每个请求显式设置它.

protected override void InitializeCulture()
{
    if (Request.Form["ListBox1"] != null)
    {
        String selectedLanguage = Request.Form["ListBox1"];
        Culture = selectedLanguage ;

        Thread.CurrentThread.CurrentCulture = 
            CultureInfo.CreateSpecificCulture(selectedLanguage);

    }
    base.InitializeCulture();
}

母版页没有InitializeCulture()调用.因此,如果要对所有页面执行此操作,则创建一个继承Page的BasePage.然后,允许所有页面从该页面继承.参见this answer

标签:date-formatting,webforms,asp-net,c
来源: https://codeday.me/bug/20191027/1948270.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有