由于公司的项目可能会卖到国外,所以需要支持多语言。今天我就在目前的项目中实现了多语言功能,下面记录我的具体实现。
1、相信很多朋友在用MVC做项目时候,都会遇到“视图必须派生自 WebViewPage 或 WebViewPage<TModel>”的错误。正如错误描述一样,MVC的视图都必须继承WebViewPage。
自定义WebViewPage类:
/// <summary> /// /// </summary> /// <remarks> /// 恒通2.0 add by zhangfj 2016/12/27 /// </remarks> /// <typeparam name="TModel"></typeparam> public abstract class HTView<TModel> : System.Web.Mvc.WebViewPage<TModel> { private ILocaleStringResourceService _localeStringResourceService { get { return Engine.Resolve<ILocaleStringResourceService>(); } } private Localizer _localizer; public Localizer Z { get { if (_localizer == null) { _localizer = (format, args) => { var resFormat = _localeStringResourceService.GetResource(format, 1); if (string.IsNullOrEmpty(resFormat)) { return new LocalizedString(format); } return new LocalizedString((args == null || args.Length == 0) ? resFormat : string.Format(resFormat, args)); }; } return _localizer; } } public override void InitHelpers() { base.InitHelpers(); } public override string Layout { get { var layout = base.Layout; if (!string.IsNullOrEmpty(layout)) { var filename = Path.GetFileNameWithoutExtension(layout); ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindView(ViewContext.Controller.ControllerContext, filename, ""); if (viewResult.View != null && viewResult.View is RazorView) { layout = (viewResult.View as RazorView).ViewPath; } } return layout; } set { base.Layout = value; } } }
然后,在Views配置文件中配置WebViewPage视图派生类为我们的自定义类:
<pages pageBaseType="IOV.Application.WebBiz.HTView"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization"/> <add namespace="System.Web.Routing" /> <add namespace="IOV.Application.Web" /> </namespaces> </pages>
最后,在视图中就可以使用我们自定义的WebViewPage:
<div class="login-container"> <div class="loginbox"> <div class="loginbox-title"> </div> <div class="loginbox-or"> <div class="or">@Z("Account.userLogin")@*用户登录*@</div> </div> <div class="loginbox-textbox"> <input type="text" class="form-control" placeholder="@Z("Account.userName")@*用户名*@" id="txtLoginName" value="admin" /> </div> <div class="loginbox-textbox"> <input type="password" class="form-control-pwd" placeholder="@Z("Account.pwd")@*密码*@" id="txtPassWord" value="123456" /> </div> <div class="col-xs-12"><span class="error-info text-danger" id="lblmsgLogin" style="margin-left: 5px"></span></div> <div class="loginbox-submit" style=" 100%; padding-left: 20px"> <input type="button" id="btnLogin" class="btn btn btn-block" onclick="DoLogin()" value="@Z("Account.login")@*登录*@"> </div> </div> <div class="logobox"> @@Copyright 2016 重庆XXXXXXX公司 </div> </div>