Is it possible to render a view outside a controller?

非 Y 不嫁゛ 提交于 2019-12-22 09:12:09

问题


I wanted to know if it was possible to render a view from a class that is not a controller. Everything I see seems to say that you can't.

What I'm trying to do is to render a partial view from a WCF web service in order to push it somewhere else. Is it possible to use the view engine for that?

Thanks!

Update:

I keep getting argument null exception with the HtmlHelper. Here is my code and the stack trace. My partial is indeed named TableOfContent.cshtml and is located in the /View/Shared folder. Do I new to instantiate my ViewContext differently?

HtmlHelper helper = new HtmlHelper(new ViewContext(), viewData);
var a = helper.Partial("TableOfContent");

   at System.Web.Mvc.ViewContext..ctor(ControllerContext controllerContext, IView view, ViewDataDictionary viewData, TempDataDictionary tempData, TextWriter writer)
   at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName)
   at SyncInvokeProcessEvent(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)

回答1:


This will call the view without requiring a controller (for the partial view).

Html.Partial(partialViewName);

See also Html.Partial method overload




回答2:


Here are two different ideas to consider:

  1. I've done something similar using RazorEngine. Allows you to render razor templates to a string.
  2. Create a controller and use WebClient to invoke the action. This assumes you have an MVC application.


来源:https://stackoverflow.com/questions/6444630/is-it-possible-to-render-a-view-outside-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!