Posted by: Cirilo Meggiolaro | 04/20/2009

Tip of the day #188 – ASP.NET MVC – Partial Views

Partial views in ASP.NET MVC web applications have similar function than user controls (ascx) in regular asp.net applications. The idea is to allow user interface functionality to be loaded and reused in an independent way with its own logic.

There is a big difference though: User controls in regular ASP.NET applications cannot be invoked directly but loaded in placeholders for example. On the other hand ASP.NET MVC action methods may request either a view or partial view to be rendered. Both views and partial views are able to load by itself but partial view may be rendered from inside a main view.

ASP.NET MVC Views inherit from System.Web.Mvc.ViewPage while Partial Views inherit from System.Web.Mvc.ViewUserControl and the files names remain the same than on ASP.NET web forms application: aspx and ascx respectively.

Rendering a partial view from inside a View

Render a partial view is pretty straightforward. Four overloads of the RenderPartial extension method are available:

  • void RenderPartial(this HtmlHelper htmlHelper, string partialViewName);
  • void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model);
  • void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData);
  • void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData);

The code snippet below requests a partial view called ProductForm to be rendered.

<% Html.RenderPartial(“ProductForm”); %>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: