使用资源将视图渲染为字符串

时间:2012-05-14 08:15:38

标签: asp.net-mvc-3 model-view-controller render culture

我有资源(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();
        }
    }

我的观点基于从用户文化中获取的资源,如何渲染视图以支持文化?

2 个答案:

答案 0 :(得分:1)

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

    @Html.ViewContext.HttpContext.GetGlobalResourceObject("resource", key, new System.Globalization.CultureInfo("de-AT")

答案 1 :(得分:1)

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

因此,您的代码应该类似于:

受保护的字符串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(); 
    } 
} 

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