Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a partial view inside a webform

Some site I'm programming is using both ASP.NET MVC and WebForms.

I have a partial view and I want to include this inside a webform. The partial view has some code that has to be processed in the server, so using Response.WriteFile don't work. It should work with javascript disabled.

How can I do this?

like image 388
eKek0 Avatar asked Mar 31 '09 19:03

eKek0


People also ask

How can I load partial view inside the view?

In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

How do I add a partial view model?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.

How do I render a partial part of a view?

You can render a partial view using Html. Action helper method. Like Html. RenderAction requires controller child action method which return PartialViewResult.

Can you have scripts in partial view?

cshtml. JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html. Action helper method, as in this section from Edit.


2 Answers

It took a while, but I've found a great solution. Keith's solution works for a lot of people, but in certain situations it's not the best, because sometimes you want your application to go through the process of the controller for rendering the view, and Keith's solution just renders the view with a given model I'm presenting here a new solution that will run the normal process.

General Steps:

  1. Create a Utility class
  2. Create a Dummy Controller with a dummy view
  3. In your aspx or master page, call the utility method to render partial passing the Controller, view and if you need, the model to render (as an object),

Let's check it closely in this example

1) Create a Class called MVCUtility and create the following methods:

    //Render a partial view, like Keith's solution     private static void RenderPartial(string partialViewName, object model)     {         HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);         RouteData routeData = new RouteData();         routeData.Values.Add("controller", "Dummy");         ControllerContext controllerContext = new ControllerContext(new RequestContext(httpContextBase, routeData), new DummyController());         IView view = FindPartialView(controllerContext, partialViewName);         ViewContext viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), httpContextBase.Response.Output);         view.Render(viewContext, httpContextBase.Response.Output);     }      //Find the view, if not throw an exception     private static IView FindPartialView(ControllerContext controllerContext, string partialViewName)     {         ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName);         if (result.View != null)         {             return result.View;         }         StringBuilder locationsText = new StringBuilder();         foreach (string location in result.SearchedLocations)         {             locationsText.AppendLine();             locationsText.Append(location);         }         throw new InvalidOperationException(String.Format("Partial view {0} not found. Locations Searched: {1}", partialViewName, locationsText));     }             //Here the method that will be called from MasterPage or Aspx     public static void RenderAction(string controllerName, string actionName, object routeValues)     {         RenderPartial("PartialRender", new RenderActionViewModel() { ControllerName = controllerName, ActionName = actionName, RouteValues = routeValues });     } 

Create a class for passing the parameters, I will call here RendeActionViewModel (you can create in the same file of the MvcUtility Class)

    public class RenderActionViewModel     {         public string ControllerName { get; set; }         public string ActionName { get; set; }         public object RouteValues { get; set; }     } 

2) Now create a Controller named DummyController

    //Here the Dummy controller with Dummy view     public class DummyController : Controller     {       public ActionResult PartialRender()       {           return PartialView();       }     } 

Create a Dummy view called PartialRender.cshtml (razor view) for the DummyController with the following content, note that it will perform another Render Action using the Html helper.

@model Portal.MVC.MvcUtility.RenderActionViewModel @{Html.RenderAction(Model.ActionName, Model.ControllerName, Model.RouteValues);} 

3) Now just put this in your MasterPage or aspx file, to partial render a view that you want. Note that this is a great answer when you have multiple razor's views that you want to mix with your MasterPage or aspx pages. (supposing we have a PartialView called Login for the Controller Home).

    <% MyApplication.MvcUtility.RenderAction("Home", "Login", new { }); %> 

or if you have a model for passing into the Action

    <% MyApplication.MvcUtility.RenderAction("Home", "Login", new { Name="Daniel", Age = 30 }); %> 

This solution is great, doesn't use ajax call, which will not cause a delayed render for the nested views, it doesn't make a new WebRequest so it will not bring you a new session, and it will process the method for retrieving the ActionResult for the view you want, it works without passing any model

Thanks to Using MVC RenderAction within a Webform

like image 40
Daniel Avatar answered Oct 18 '22 16:10

Daniel


I had a look at the MVC source to see if I could figure out how to do this. There seems to be very close coupling between controller context, views, view data, routing data and the html render methods.

Basically in order to make this happen you need to create all of these extra elements. Some of them are relatively simple (such as the view data) but some are a bit more complex - for instance the routing data will consider the current WebForms page to be ignored.

The big problem appears to be the HttpContext - MVC pages rely on a HttpContextBase (rather than HttpContext like WebForms do) and while both implement IServiceProvider they're not related. The designers of MVC made a deliberate decision not to change the legacy WebForms to use the new context base, however they did provide a wrapper.

This works and lets you add a partial view to a WebForm:

public class WebFormController : Controller { }  public static class WebFormMVCUtil {      public static void RenderPartial( string partialName, object model )     {         //get a wrapper for the legacy WebForm context         var httpCtx = new HttpContextWrapper( System.Web.HttpContext.Current );          //create a mock route that points to the empty controller         var rt = new RouteData();         rt.Values.Add( "controller", "WebFormController" );          //create a controller context for the route and http context         var ctx = new ControllerContext(              new RequestContext( httpCtx, rt ), new WebFormController() );          //find the partial view using the viewengine         var view = ViewEngines.Engines.FindPartialView( ctx, partialName ).View;          //create a view context and assign the model         var vctx = new ViewContext( ctx, view,              new ViewDataDictionary { Model = model },              new TempDataDictionary() );          //render the partial view         view.Render( vctx, System.Web.HttpContext.Current.Response.Output );     }  } 

Then in your WebForm you can do this:

<% WebFormMVCUtil.RenderPartial( "ViewName", this.GetModel() ); %> 
like image 196
Keith Avatar answered Oct 18 '22 16:10

Keith