How to change default view location scheme in ASP.NET MVC?

前端 未结 5 472
甜味超标
甜味超标 2020-11-27 02:45

I want to change view locations at runtime based on current UI culture. How can I achieve this with default Web Form view engine?

Basically I want to know how implem

5条回答
  •  时光说笑
    2020-11-27 03:20

    Below is a localized view engine without the rewrite.

    In a nutshell, the engine will insert new locations into the view locations everytime a view is looked up. The engine will use the two character language to find the view. So if the current language is es (Spanish), it'll look for ~/Views/Home/Index.es.cshtml.

    See code comments for more details.

    A better approach would be to override the way view locations are parsed, but the methods are not overridable; maybe in ASP.NET MVC 5?

    public class LocalizedViewEngine : RazorViewEngine
    {
        private string[] _defaultViewLocationFormats;
    
        public LocalizedViewEngine()
            : base()
        {
            // Store the default locations which will be used to append
            // the localized view locations based on the thread Culture
            _defaultViewLocationFormats = base.ViewLocationFormats;
        }
    
        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            AppendLocalizedLocations();
            return base.FindPartialView(controllerContext, partialViewName, useCache:fase);
        }
    
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            AppendLocalizedLocations();
            returnbase.FindView(controllerContext, viewName, masterName, useCache:false);
        }
    
        private void AppendLocalizedLocations()
        {
            // Use language two letter name to identify the localized view
            string lang = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
    
            // Localized views will be in the format "{action}.{lang}.cshtml"
            string localizedExtension = string.Format(".{0}.cshtml", lang);
    
            // Create an entry for views and layouts using localized extension
            string view =  "~/Views/{1}/{0}.cshtml".Replace(".cshtml", localizedExtension);
            string shared =  "~/Views/{1}/Shared/{0}".Replace(".cshtml", localizedExtension);
    
            // Create a copy of the default view locations to modify
            var list = _defaultViewLocationFormats.ToList();
    
            // Insert the new locations at the top of the list of locations
            // so they're used before non-localized views.
            list.Insert(0, shared);
            list.Insert(0, view);
            base.ViewLocationFormats = list.ToArray();
        }
    }
    

提交回复
热议问题