Andy
Andy

Reputation: 11512

Best way to allow postback on a gridview without viewstate

My gridview is basically a hit list of results from which the user selects one, and I want to get a postback saying which one he has selected. There is no need for the grid contents to survive the postback round-trip because the hit list disappears as soon as he has selected an item.

I don't want to use viewstate because the hit list is likely to be large. I don't want to databind from the database in PageLoad to repopulate the grid because the search may take a while.

what I'm thinking at the moment is that I can put some javascript on the 'select' link to store the ID of the selected item in a hidden field and then call __doPostBack

this still seems a bit clunky. can you think of a cleaner way?

Upvotes: 0

Views: 2828

Answers (2)

SouthShoreAK
SouthShoreAK

Reputation: 4296

Is the ID of the selected item something sensitive that should not be seen by the user?

If it is not, you could just make your select button a link to the next page, with the ID as a querystring variable. Clicking would just move to the next page, no postback required.

Upvotes: 0

James Johnson
James Johnson

Reputation: 46077

If the postback should be triggered when the user clicks the anywhere in the row, use the ItemDataBound event to attach a client onclick handler:

protected void GridView1_ItemDataBound(object sender, GridViewRowEventArgs e)
{
    var dataItem = e.Item as GridViewRow;
    if (dataItem != null)
    {
        dataItem.Attributes["onclick"] = string.Format("__doPostBack(this, '{0}')", e.Row.RowIndex);
    }
}

Upvotes: 2

Related Questions