views:

217

answers:

4

Hello, everybody.

I'm developing a little application in ASP.NET MVC.

This app has a lot of "HTML pieces" that are used many times with a little variance.

For this pieces, I'm using strongly-typed partial views.

My question is: This is the right way to reuse code in View layer? Is there some inconviniece to use partials views?

Thanks a lot.

+3  A: 

Personally, I think it's a great way of reducing the duplication in your HTML and do it all the time. Just avoid doing things with them that you should be doing through nested master pages and so forth.

As a rule of thumb, you shouldn't have nested partial views.

Garry Shutler
Dang, another person beat me by a few seconds.
Martin
A: 

i think it is a good thing. Especially if you want your differents page to use the same behaviour: example, I put my mvccontrib pager in the shared folder so all my pagers look the same way.

I have got only one inconvenience with partials view for the moment: when updating in ajax a part of my container with a partial view, the javascript of this partial view is not always taken in account.

Gregoire
+1  A: 

I've found strongly typed views, whether "full" or partial ones to be greatly beneficial. Otherwise you'd be stuck with a lot of ViewData code that isn't pretty and harder to debug.

If you find yourself jumping through a lot of hoops to get the models to work properly, consider wrapping the smaller ones in a bigger "context" type object:

public class ViewModelA {
 public string Name { get; set; }
}

public class ViewModelB {
 public int Id { get; set; }
}

public class ViewModelContext {
 public ViewModelA { get; set; }
 public ViewModelB { get; set; }
}

And have your View take a ViewModelContext as the type. This will let you access all of the other models quickly.

swilliams
+1  A: 

Typically I put a lot of the common code in the MasterPage. I use partial views for larger, self-contained units of functionality. For example, a grid that gets reused across many but not all pages or the header login "controls." Sometimes it's a combination of the two. For example, my main, unauthenticated menu items appear in the MasterPage mark up, but I use a partial view for my authenticated menu items which contains the logic for dealing with which items show depending on the user's role.

The other thing that you might want to think about for small HTML snippets is HtmlHelper extensions. I find that this is a good way to set up particular kinds of HTML elements. For example, I have an extension that will add a "button" that will work with either javascript enabled (renders as an anchor) or disabled (renders a button inside a noscript tag). This sort of thing is better as an extension, in my mind anyway, than a partial view since it's not really a "view" of anything.

tvanfosson