views:

372

answers:

2

Hi All,

I am wondering if it is possible to wrap up an ascx file so that it can be used in different views, without having to type it to a specific Model.

This would mean you could use one ascx file for many pages, as long as the relevant model data was passed in.

Currently I'm duplicating my ascx files for different parts of the site, but this feels very un DRY.

ps this is th kind of model I'm passing in.

public class DinnerPage {
public Dinner dinner {get; set;} //main page data
public List<Dinner> Random6Dinners {get; set;} // ascx content
}

The problem is if I want to use the ascx file that renders the 6 random dinners, but for a different main page, then I have to type it differently.

Basically, can you have an untyped ascx page (or a view)

Thanks all.

+3  A: 

I believe what you are asking is if you could re-use many views like a control on a single view? If so, you can indeed. Use the Html.RenderPartial action in your view. This will render an existing "aspx" page on your current view:

Example:

Assuming Model.Dinners is a List/Enumrable of some sort.

Dinners.aspx

<!--html-->

<%foreach(var dinner in Model.Dinners){%>
 <% Html.RenderPartial("~/DinnersFolder/Dinner.ascx", new { Dinner = dinner}); %>
<%}%>

<!--html-->

Dinner.aspx

 <%
  var dinner = ViewData.Eval("Dinner");
 %>
 <!--html-->

Something like this would work for an individual dinner:

 <% Html.RenderPartial("Dinner", Model.Dinner); %> //Dinner being Dinner.ascx

This way your ("MyPartialView" / MyPartialView.aspx), will take in a type of Dinner. You can then pull out that Dinner via ViewData.Eval, and display your "Dinner" accordingly.

In your main page you can: then do something like foreach Dinner in my Dinners, render a PartialControl.

A detailed example of this:

You could aslo use RenderAction, this has the same exact idea. However, it will post to your Controllers action, which in turn returns a view:

<% Html.RenderAction(...); %> 

This is a great article about the difference between each, and which you should use:

Andrew
Haven't got time to test this now, but it makes SO much sense that you could pass models like this, from main view to ascx. Will let you know how I get on.
optician
Great, good luck feel free to ask any more questions.
Andrew
A: 

Have you tried having a base Dinner model in which the 6 random dinner classes derive from and then just use the user control as such:

<%= Html.RenderPartial("DinnerControl", 
                       Model.RandomDinnerThatDerivesFromBaseDinner); %> 

And then the first line of your control should be something like:

<%@ Control Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<BaseDinner>" %>
jamesaharvey