asp.net-mvc - 如何在 ASP.NET MVC4 Api Controller 中将 View 呈现为字符串

标签 asp.net-mvc asp.net-mvc-4 razor asp.net-web-api razor-2

ASP.NET MVC4 Web API Controller 应将 Razor View 作为 json 结果属性中的 html 返回。

我试过 Controller

public class TestController : ApiController
{
    public HttpResponseMessage Get()
    {
        var body = RenderViewToString<object>("~/Views/Broneeri/Schedule.cshtml", new object() );
        return Request.CreateResponse(HttpStatusCode.OK, new { content = body } );
    }

    string RenderViewToString<T>(string viewName, T model)
    {
        ViewDataDictionary ViewData = new ViewDataDictionary(model);
        TempDataDictionary TempData = new TempDataDictionary();
        ControllerContext controllerContext = new System.Web.Mvc.ControllerContext();
        controllerContext.RouteData = new RouteData();

        controllerContext.RouteData.Values.Add("controller", "Schedule");
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
            var viewContext = new ViewContext(controllerContext, viewResult.View, ViewData,          
                       TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
 }

但我有一个奇怪的异常(exception)
System.NotImplementedException was unhandled by user code
  HResult=-2147467263
  Message=The method or operation is not implemented.
  Source=System.Web
  StackTrace:
       at System.Web.HttpContextBase.get_Items()
       at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations)
       at System.Web.Mvc.VirtualPathProviderViewEngine.FindPartialView(ControllerContext controllerContext, String partialViewName, Boolean useCache)
       at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
       at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
...

在线
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);

如何从 ASP.NET 4 Web API Controller 的 View 中返回 HTML 内容?

最佳答案

您需要Install-Package RazorEngine使用您的 NuGet 控制台。这是对我有用的代码:

using RazorEngine;
using RazorEngine.Templating;

string razorTemplate = "Hello @Model!";
string html = Engine.Razor.RunCompile(
    razorTemplate, 
    "uniqueTemplateKey", // Guid.NewGuid().ToString() for example
    modelType: typeof(string), 
    model: "Lorem Ipsum");

希望能帮助到你!

关于asp.net-mvc - 如何在 ASP.NET MVC4 Api Controller 中将 View 呈现为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26821479/

相关文章:

c# - Visual Studio 2012 和 MVC 4 : How to deploy individual files/folders to filesystem?

C#.NET MVC- HTTP 错误 403.14 - 禁止 Web 服务器配置为不列出此目录的内容

razor - 输入隐藏显示不正确的 ID (Guid.Empty)

asp.net-mvc - ViewModel 集合属性在 MVC 3 中回发到 Controller 操作后丢失值

asp.net - MVC 中同一页面上有多个 ViewModel

asp.net-mvc - Mvc jquery 验证提供哪些优势?

c# - 生成的 LINQ 类的动态属性访问

c# - 使用 <text> 标签的 MVC .Net 4 Razor 问题

asp.net-mvc - MVC Razor 中的 Foreach 循环计数器

c# - MVC RouteConfig "CatchAll"{*url} 不工作