tags:

views:

11

answers:

1

Consider a ViewComponent that renders paging navigation. One of the parameters passed to the component is the current PageIndex (index of the viewed page).

How can I use this passed value in my ViewComponents template without putting it into the ViewData?

-- ViewComponent:

[ComponentName("GalleryPager")]
public class PagerComponent : ViewComponent
{
    [Parameter("PageIndex")]
    private int _pageIndex;

    public void Run()
    {
        ... some logic ...

        ViewData["PageIndex"] = _pageIndex; // I want to avoid this!
    }
}

-- Parent view:

...
<span class="paging">
    {% GalleryPager @PageIndex = SOME_VALUE %}
</span>
...

-- Component view:

...
<span class="page_index">
    {{ PageIndex }} <!-- This way it's passed/used as ViewData -->
</span>
...
+1  A: 

I'm afraid this is not possible. View components are designed in to behave in an isolated manner, which implies that no view data variables are secretly added when rendering the view component's template.

This is the intended behavior. What if the call to the view component would pass all parameters on to the view component as view data? That could create a security hole when you allow end-users to create their own templates. If they could call view components and mess with the view data passed to the view component, you could create a serious security risk.

Philippe Leybaert