开发者

Where is the correct place to do culture-specific date/currency formatting for asp.net mvc views?

Given a domain object:

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

    public decimal BirthdayPresent { get; set; }
}

I have two options for passing this to a strongly-typed view:

1.

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

    public decimal BirthdayPresent { get; set; }
}

and in the view

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

2.

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

    public string BirthdayPresent { get; set; }
}

and in the controller (for instance)

BirthdayDomain bd = Repository.GetBirthday(.....)
BirthdayView bv = new BirthdayView()
                  {
  开发者_Go百科                     Birthday = bd.Birthday.ToString("d");
                       BirthdayPresent = bd.BirthdayPresent.ToString("C2");
                  }

and in the view just output the strings.

My question is this: if I want to support the user's (browser's?) current locale settings so that dates and currencies are displayed the way theu expect, where is the best place to do this? Can it be done in either the view or the controller? What is the generally-accepted technique for handling this?


If you want to support browser language put this in your web.config:

<globalization culture="auto" />

And in your view:

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

ACCEPT-LANGUAGE request header will be used to set the culture and format the date accordingly.


Typically you want want to do all your string manipulation in your model. When your controller instantiates a new model, pass it the local information so the model can properly format the date for you. Another option would be be to have the model pull the local information out of the context of the request. Just be sure to get your logic into the model.


I put culture formatting in the view because in my opinion it is its role and the data sent by the controller stays strong typed and not becomes basic string. At least for the auto-completion in your dev environment it is a bonus...

EDIT

You can also change the current Thread UI culture in your controller, if you do not want to specify whuich culture to use every time there is a ToString in your views.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜