如何编写一个方法并传递参数并在每个控制器中调用它? 问题:我基本上在RouteConfig文件上设置了本地化:
routes.MapRoute(
name: "Default",
url: "{language}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, language = "en-US" }
);
当用户更改语言时,我在Url.ActionLink上发送参数“ languageCulture”(例如:“ en-US”)。
因为我出于个人目的创建了一个网站,所以我在Home controller中创建的每个方法都将是一个单独的网页。现在我得到了重复的代码:
public class HomeController : BaseController
{
GlobalModel gm;
public HomeController()
{
gm = new GlobalModel();
}
public ActionResult Index(string language)
{
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
gm.CultureCode = language;
return View(gm);
}
catch (System.Exception ex)
{
throw ex;
}
}
public ActionResult Services(string language)
{
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
gm.CultureCode = language;
return View(gm);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
我创建了一个GLobal模型类,其中包含有关文化的信息。我需要它,因为我想基于jQuery中的“标志”为语言标签着色。
我的问题是: 我该如何在BaseController中编写方法,例如:
public class BaseController : Controller
{
public ActionResult SetCulture(string language)
{
//implementation something like
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
GlobalModel gm = new GLobalModel();
gm.CultureCode = language;
return RedirectToAction();
}
}
如何从此方法调用Home控制器中的特定方法?我是否需要传递其他参数我要调用的方法,还是有一些“更简单”的解决方案?