Monday, January 20, 2014

Displaying an ascx control within MVC Razor view (as partial view)

In this blog, I would like to talk about including ascx controls within MVC pages and display them.

    Though, this one is not the preferred approach in general, but still if needed for common scenarios with avoidable runat=Server attribute elements, then yes, we can implement the below...

   Though I was able to successfully do this, but I was not successful in implementing the server side controls within the .ascx controls or .aspx pages. (will be glad to know if  any one did this way)

Lets see an example of how this can be achieved.

   In your MVC project,
  • navigate to Views and right click to select Add new item. 
  • Select a web user control and name it testview.ascx
  • Implement any basic html text and display any items you want to and save it.
  • Go to your MVC view (any .cshtml file ) that needs to display this control.
  •  Add this line, where the control should show up.. @(Html.Partial("testview",null));
Also, make sure the following changes are done, before running the project..

RegisterRoutes method should be defined as below..

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Also delete the code behind files and designer files.  

This should be good enough to get you started.....


No comments:

Post a Comment