代码之家  ›  专栏  ›  技术社区  ›  Jedidja

asp.net mvc视图的区域性特定日期/货币格式设置的正确位置在哪里?

  •  1
  • Jedidja  · 技术社区  · 16 年前

    class BirthdayDomain
    {
        public DateTime Birthday { get; set; }
    
        public decimal BirthdayPresent { get; set; }
    }
    

    我有两个选项可以将其传递给强类型视图:

    1.

    class BirthdayView
    {
        public DateTime Birthday { get; set; }
    
        public decimal BirthdayPresent { get; set; }
    }
    

    <%: Model.Birthday.ToString("d"); %>
    <%: Model.BirthdayPresent.ToString("C2"); %>
    

    2.

    class BirthdayView
    {
        public string Birthday { get; set; }
    
        public string BirthdayPresent { get; set; }
    }
    

    在控制器中(例如)

    BirthdayDomain bd = Repository.GetBirthday(.....)
    BirthdayView bv = new BirthdayView()
                      {
                           Birthday = bd.Birthday.ToString("d");
                           BirthdayPresent = bd.BirthdayPresent.ToString("C2");
                      }
    

    在视图中只输出字符串。

    3 回复  |  直到 16 年前
        1
  •  2
  •   Darin Dimitrov    16 年前

    如果您想支持浏览器语言,请将其放在web.config中:

    <globalization culture="auto" />
    

    在你看来:

    <%= Html.Encode(DateTime.Now.ToString()) %>
    

    ACCEPT-LANGUAGE请求头将用于设置区域性并相应地设置日期格式。

        2
  •  0
  •   George English    16 年前

        3
  •  0
  •   Gregoire    16 年前

    我将区域性格式化放在视图中,因为在我看来,它是它的角色,控制器发送的数据保持强类型,而不是成为基本字符串。至少对于开发环境中的自动完成来说,这是一个额外的好处。。。

    编辑

    如果不希望每次视图中有ToString时都指定要使用的区域性,还可以更改控制器中的当前线程UI区域性。