For a Web application that needs to support multiple languages, a common use is to control the language and culture on which the interface is presented by requesting addresses, For example, we will be in the URL of the request address in the language culture code (such as en or en-us) to guide the server should use what language to display the content of the interface. For a asp.net MVC application, it is easy to implement such a function through URL routing.
Before we introduce the implementation, we'll talk about the effect of the final implementation in a simple example. In an empty Web application created through the ASP.net MVC project template, we created the following homecontroller, the default action method index, which is used to render a login view. The Logininfo class as model contains the username and password two properties, representing the user name and password entered for the login, respectively. It should be noted that DisplayAttribute is applied on two properties and the display name is specified in a resource manner to enable support for multiple languages.
1:public class Homecontroller:controller
2: {
3: Public actionresult Index ()
4: {
5: Return View (new Logininfo ());
6: }
7:}
8:
9:public class Logininfo
10: {
One: [Display (Name = "UserName", ResourceType = typeof (Resources))]
: Public string UserName {get; set;}
13:
[Display (name= "Password", ResourceType = typeof (Resources))]
: [DataType (Datatype.password)]
: Public string Password {get; set;}
17:}
The definition of the view that corresponds to the action method index, as shown below, is a strongly typed view based on Loginfo.
1: @model MvcApp.Models.LoginInfo
2: @using (Html.BeginForm ())
3: {
4: @Html. Editorformodel ()
5: <input type= "Submit" value= "@MvcApp. Properties.Resources.Login"/>
6: <input type= "button" value= "@MvcApp. Properties.Resources.Cancel"/>
7:}
In Global.asax, we modified the URL route registration code that was added by default, so that the request URL contains the appropriate language culture information ({culture}).
1:public class MvcApplication:System.Web.HttpApplication
2: {
3: //other Members
4: Public static void RegisterRoutes (RouteCollection routes)
5: {
6: //Other operations
7: routes. Maproute (
8: Name: "Default",
9: URL: "{culture}/{controller}/{action}/{id}",
defaults:new {culture= "en", controller = "Home", action = "Index", id = urlparameter.optional}
One: );
: }
13:}
We run the program directly and specify different culture (en and en) in the request address, which is based on the language we expect.