Is it possible to render a view outside a controll

2019-05-03 18:03发布

问题:

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.