views:

403

answers:

1

My MVC application contains a parent model, which will contain 1 or more child models.

I have set up the main view to display properties from the parent model, and then loop through a collection of my child models (of various types, but all inheriting from the same base type). Each of the child models have a corresponding partial view.

My "parent" view iterates over the child models like this:

foreach (ChildBase child in ViewData.Model.Children)
{
  Html.RenderPartial("Partials/"+child.ChildType.ToString()+"Child", 
    section);
}

My application has the appropriate /Partials/ChildType1.ascx, ChildType2.ascx, etc. Everything works great.

  1. Is this an appropriate way to use Partial Views? It feels slightly off-kilter due to the dynamic names, but I don't know another way to perform dynamic selection of the proper view without resorting to a big switch statement.

  2. Is it advisable to use the same view for multiple "modes" of the same model? I would like to use the same .ascx for displaying the "read only" view of the model, as well as an edit form, based on which Controller Action is used to return the view.

+1  A: 

Iconic,

It's difficult to answer the questions without knowing exactly what you're trying to achieve.

I'll have a go though:

If you're familiar with web forms, think of your partial view as a webforms usercontrol for the moment and think of the part of your model that is relevant to your partial views as a 'fragment of information' that want to pass across to the partial view.

Natural choices for using a partial view would be for elements used in many views across your site.

So ... in answer:

1.Although what you are doing is valid, it doesn't seem quite correct. An example of a partial view I have used might be a row in a grid of data where you'd call the partial view passing in the row object as its model:

    foreach (MyObject o in Model.objects)
{
  Html.RenderPartial("Shared/gridRowForObject.ascx", o, ViewData);
}

You can strongly type your views also to expect a specific type to be passed through as the Model object.

Again another use might be a login box or a 'contact me form' etc.

2._Ultimately this is a personal design decision but I'd go for the option that requires the least application/presentation logic and the cleanest code in your view. I'd tend to avoid writing to many conditional calls in your view for example and by inferring a base type to pass across to all of your partial views as in your example, may well tie you down.

When learning the MVC framework I found the Oxite code to be useful.

I hope that helps.

Lewis