但是我更喜欢在类库中有一个ViewUserControl或者仅仅一个ViewPage,这样可以进行渲染。我希望能够使用ViewUserControl和渲染方法
从一个ASP.NETMVC应用程序,例如Windows服务。
如何从类库渲染视图?
我尝试了这个,但是对RenderPartial的调用抛出了一个NullReferenceException。
[TestMethod]
public void RenderViewToString()
{
string viewName = "EmailTest";
string viewData = "martin";
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(new HttpRequest("fake.html", "http://localhost/fake.html", ""), fakeResponse);
var fakeRouteData = new RouteData();
fakeRouteData.Values.Add("Controller", "Fake");
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), fakeRouteData, new FakeController());
HttpContext.Current = fakeContext;
var html = new HtmlHelper(new ViewContext(fakeControllerContext, new FakeView(), new ViewDataDictionary(), new TempDataDictionary(), memWriter), new ViewPage());
html.RenderPartial(viewName, viewData);
memWriter.Flush();
var htmlString = sb.ToString();