开发者

Is it possible to render a view outside a controller?

开发者 https://www.devze.com 2023-03-14 14:26 出处:网络
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.

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.Part开发者_如何学GoialExtensions.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)


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

Html.Partial(partialViewName);

See also Html.Partial method overload


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号