It's a little unclear for me on when to use a custom helper method and when to use RenderAction and also when to simply use ViewData instead. Some of their functions overlap slightly.
For example, if I were to create a Category navigation bar, would I create a new helper method and place that in some partial view? I had initially though of doing this, but I read on some blog to use RenderAction instead. I've just been thinking back and forth and could use some help not just with this example, but in general.
Assume the list of categories is coming from some data source.
The general guidelines that I follow are:
HtmlHelper methods:
Render partial:
Render action:
ViewData:
I'll use ViewData to track global data that applies to all views, such as the current user. If I need a consistent way of displaying this data I usually create a partial for it and then do RenderPartial() in a master page.
Firstly, this is probably clear, but let's say it: The category business logic (eg fetching data from a data source) should not be in Html-helper or in a user control: it should be done in a controller.
The difference between 1) RenderPartial / HtmlHelper vs. 2) RenderAction is in which controller this business logic is:
If you use your category data in pretty much every page I do not see it wrong to fetch it for each page on page-controller action level and pass it in the view data. Of course you would use some mechanism (custom model base class, extend controller, ...) so that you don't have the same category-fetching function call in each action (assuming you have lots).
If some page views choose to show the categories, some not and some perhaps have another category control with different business logic, then RenderAction is definitely better. Even in the above case, RenderAction is good: it separates the category fetching from other data in your controller actions.
Then whether to use RenderPartial or HtmlHelper... To me HtmlHelpers should be more generic and not specific to particular view or model, but this, I suppose, is more matter of taste than clear rule from MVC perspective: both should be just View-logic.
I would choose html helper methods when the scenario meets these criteria:
If you have an html helper method using model data or it has a lot of dependencies, its probably better as a RenderPartial or RenderAction.
I'm new also to using RenderAction
but when I need to load data for a specific piece of display I now go with RenderAction
Ideal for loading Tag cloud, which are displayed on every page but the data is not specific to a page.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.