Jimmyt1988
Jimmyt1988

Reputation: 21166

Preparing an object that references a lambda variable before lambda even defined

This helper outputs pagination:

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    index => Url.Action( 
        "List", 
        "Test", 
        new { 
            page = index, 
            amount = 10, 
            sort = Request.Params[ "sort" ], 
            order = Request.Params[ "order" ] 
        } 
    ),
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
) 

The BootstrapPager function's second parameter is a lambda. The index variable is referencing the internal loop that outputs page numbers.

Is there any way you can think of that allows me to pre-prepare the object being passed in as the 3rd parameter of Url.Action that still references the lambda index variable?

It might look like this:

object myActionData = new { 
    page = <index>, // I don't know how this line would work
    amount = 10, 
    sort = Request.Params[ "sort" ], 
    order = Request.Params[ "order" ] 
}    

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    index => Url.Action( 
        "List", 
        "Test", 
        myActionData        
    ),
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
) 

Upvotes: 1

Views: 76

Answers (1)

Falanwe
Falanwe

Reputation: 4744

That's not possible, the whole point of having a lambda here is that index is not set before the lambda is effectively called.

The best you can do is declare the factory function beforehand.

@{
    Func<int, object> myActionDataFactory = index => new { 
        page = index, // Here we use the parameter
        amount = 10, 
        sort = Request.Params[ "sort" ], 
        order = Request.Params[ "order" ] 
    };
}

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    index => Url.Action( 
        "List", 
        "Test", 
        myActionDataFactory(index)
    ),
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
) 

Likewise, you can remove the whole lambda from the BootstrapPager call.

@{
    Func<int, sting> myUrlFactory = index => Url.Action( 
            "List", 
            "Test",
            new { 
                page = index, // Here we use the parameter                
                amount = 10, 
                sort = Request.Params[ "sort" ], 
                order = Request.Params[ "order" ] 
            });
}

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    myUrlFactory,
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
)

You can even declare your Url factory as a method of a (presumably static) class you declare elsewhere in your code.

Upvotes: 4

Related Questions