Question

I have a datalist that receives values from a MySQL database. This datalist can be sorted by various column values such 'Title', 'Author', 'Published Date', etc. To determine what value to sort by, the value is inserted into the query string.

I.e. www.web.com/default.aspx?order_by=title

I also determine wheter to order in ascending order or descending order.

I.e. www.web.com/default.aspx?order_by=title&direction=asc

I want to be able to set the direction to asc if the

(a working example of what I'm looking to do can be found at

http://www.milwaukeejobs.com/jobs/category/Information-Technology-Internet-Web-Development/Milwaukee,-WI/1306

*Notice if you click the sort values such as by Date its set to ASC, if you click it again its set to DSC; I'd like to do this on my site * )

I'm not sure how to do this. I was thinking of a If Page.IsPostback condition, but clicking the url does not cause a postback. I thought about grabbing the sender object, or system.eventargs variables that are sent through the Page.Onload event, but I'm not sure if I could do anything with these. Any ideas?

Was it helpful?

Solution

I would maintain the sort order of the columns within the page itself as hidden input fields (with runat="server" specified). When a link is clicked, you can flip the direction of this field prior to postback. This gets around having to check for IsPostBack status.

Something like this:

<input type="hidden" id="TitleSortOrder" Runat="server" />
<asp:LinkButton id="TitleHeader" onclick="return(FlipSortOrder('Title'));" />

function FlipSortOrder(type)
{
  var sortOrder = document.getElementById(type + "SortOrder");
  sortOrder.value = sortOrder.value === "ASC" ? "DESC" : "ASC";
  return true;
}

In server-side code, you can refer to the value of the title sort direction using the TitleSortOrder.Value property.

To make this work in MySQL, you'll need to execute a dynamic query if you intend for the sorting to happen at the database level. This is similar to post Dynamic Column name in MYSQL, but in the interests of keeping this all together, the pattern of executing dynamic SQL in MySQL looks like this:

SET @qry = 'your query here';
PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top