1

我有资源 (resx) 文件和视图,我需要呈现以发送邮件。我使用这个解决方案:

 protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }

我的视图基于从用户文化中获取的资源,如何呈现视图以支持文化?

4

2 回答 2

1

基本上你可以这样做或者将它封装在你自己的辅助方法中。

    @Html.ViewContext.HttpContext.GetGlobalResourceObject("resource", key, new System.Globalization.CultureInfo("de-AT")
于 2012-05-14T08:30:10.367 回答
1

我认为您需要将当前线程的 CurrentUICulture 设置为您要使用的文化。为此,您需要以下代码: Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");//语言名称可能是一个参数 Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

所以你的代码应该是这样的:

protected string RenderPartialViewToString(string viewName, object model, string languageName) { if (string.IsNullOrEmpty(viewName)) viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model; 

    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(languageName);//The language name will probably be a parameter
    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

    using (StringWriter sw = new StringWriter()) 
    { 
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); 
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); 

        viewResult.View.Render(viewContext, sw); 

        return sw.GetStringBuilder().ToString(); 
    } 
} 

您的视图将以您需要的语言呈现。

于 2012-05-15T10:52:58.707 回答