首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 透過 URL 路由實現多語言支援

     編輯:關於ASP.NET

對於需要支援多語言的 Web 應用程式,常見的做法是透過請求 URL 中的文化特性代碼(如 en 或 en-US)來決定伺服器以何種語言呈現介面內容。在 ASP.NET MVC 中,我們可以輕鬆利用 URL 路由機制來達成這項功能。

實作範例

首先建立一個簡單的 HomeController,其預設 Index 動作方法回傳一個登入視圖。作為模型的 LoginInfo 類別包含 UserName 與 Password 兩個屬性,並透過 DisplayAttribute 搭配資源檔指定顯示名稱,以實現多語言支援。

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new LoginInfo());
    }
}

public class LoginInfo
{
    [Display(Name = "UserName", ResourceType = typeof(Resources))]
    public string UserName { get; set; }

    [Display(Name = "Password", ResourceType = typeof(Resources))]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

對應的強型別視圖定義如下:

@model MvcApp.Models.LoginInfo
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="@MvcApp.Properties.Resources.Login" />
    <input type="button" value="@MvcApp.Properties.Resources.Cancel" />
}

路由設定

在 Global.asax 中修改預設路由註冊程式碼,使請求 URL 包含文化特性資訊({culture}):

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            name: "Default",
            url: "{culture}/{controller}/{action}/{id}",
            defaults: new { culture = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

執行程式並在請求網址中指定不同的 Culture(如 en 與 zh),介面即會依預期呈現對應語言。

多語言路由示例

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved