Skip to content

Instantly share code, notes, and snippets.

@carloswm85
Last active October 25, 2024 16:31
Show Gist options
  • Save carloswm85/1e2547e41b1a2ecea54893dfa1a173ba to your computer and use it in GitHub Desktop.
Save carloswm85/1e2547e41b1a2ecea54893dfa1a173ba to your computer and use it in GitHub Desktop.
Datatables implementation, backend only.
/// <summary>
/// Retrieves a paginated list of trackers for a given request, supporting sorting, searching, and pagination.
/// Returns an object tailored for listing, <see cref="ListedTrackerDto"/>.
/// This method may be used with frontend calls compatible with DataTables.
/// </summary>
/// <param name="requestId">The ID of the specific request for which trackers are being retrieved.</param>
/// <returns>A JSON object containing paginated tracker data, total records, and any error messages if an exception occurs.</returns>
[HttpPost]
public virtual ActionResult GetTrackerPaginatedList(int requestId)
{
// Retrieve the current user ID from the account service to ensure access is scoped to this user
int userId = _accountService.UserID;
try
{
// DataTables Parameters: fetch values from the form data, using safe fallback values
string draw = Request.Form["draw"] ?? string.Empty; // Unique identifier for the DataTables request
string start = Request.Form["start"] ?? "0"; // Starting index of records (pagination)
string length = Request.Form["length"] ?? "10"; // Number of records to return (page size)
string sortColumn = Request.Form[$"columns[{Request.Form["order[0][column]"]}][name]"] ?? string.Empty; // Column to sort by
string sortColumnDirection = Request.Form["order[0][dir]"] ?? "asc"; // Sort direction (asc or desc)
string searchedValue = Request.Form["search[value]"] ?? string.Empty; // Search query entered by the user
// Parse pagination parameters safely
int pageSize = int.TryParse(length, out int len) ? len : 10;
int skip = int.TryParse(start, out int st) ? st : 0;
// Fetch the list of trackers with IQueryable for deferred execution
IQueryable<ListedTrackerDto> listedTrackers = _trackerService.GetListedTrackerQueryable(userId, requestId);
// Apply search filter: match trackers by various properties if a search value is provided
if (!string.IsNullOrEmpty(searchedValue))
{
listedTrackers = listedTrackers.Where(m => m.TrackerCode.Contains(searchedValue)
|| m.MineralName.Contains(searchedValue)
|| m.ExpeditionDate.Contains(searchedValue)
|| m.ExpeditionTime.Contains(searchedValue)
|| m.MineralQuantity.Contains(searchedValue));
}
// Count the total records after filtering, for pagination
int recordsTotal = listedTrackers.Count();
// Apply sorting dynamically if a valid column and direction are provided
if (!string.IsNullOrEmpty(sortColumn) && !string.IsNullOrEmpty(sortColumnDirection))
{
// Dynamically build an order expression using LINQ's dynamic sorting syntax
listedTrackers = listedTrackers.OrderBy($"{sortColumn} {sortColumnDirection}");
}
// Handle pagination: retrieve a subset based on page size if provided
List<ListedTrackerDto> listedTrackersJson = pageSize < 0
? listedTrackers.ToList() // No pagination, return all records
: listedTrackers.Skip(skip).Take(pageSize).ToList(); // Skip and take for paginated results
// Return JSON response in a DataTables-compatible format
return Json(new { draw, recordsFiltered = recordsTotal, recordsTotal, data = listedTrackersJson });
}
catch (Exception ex)
{
// Log the error with additional context, capturing user ID and request ID for debugging
string errorId = LogHelper.LogError(ex, "Tracker", "GetTrackerPaginatedList");
//string errorId = LogHelper.LogError(ex, "Tracker", "GetTrackerPaginatedList", $"UserId: {userId}, RequestId: {requestId}");
// Return a JSON response with a user-friendly error message and type
return Json(new
{
type = Config.ReturnViewType.Alert, // Return an alert to inform the user of the error
data = string.Format(Resources.Global.TRY_CATCH_ERROR_MESSAGE, errorId) // Display a general error message with log reference
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment