ASP MVC: Counting and Recording Link Clicks
Sometimes we need to count the number of times visitors click on standard HTML <a href.. links. A typical example would be if we had affiliate links to our page and we want to know how many times the user clicked on them. Often these links will open in a new window. Besides a count, we may want to add the URL and user information to a database for future stats.
There are a number of ways to do this, such as jQuery and an AJAX call, but you can use the power of ASP MVC and the Html helper ActionLink.
@Html.ActionLink( "More Details", // text of the link "RecordClick", // the Action function in your controller "Home", // the Controller name new { id = "lr1", thisUrl = @Model.WebAddress }, // id and passed parameter new { @class = "btn btn-sm btn-link", target = "_blank" } // css and open in new window )
So for this example we will be on the Home Controller, so define the action function there:
public ActionResult RecordClick(string thisUrl) { // .. // log what you need here // .. // finally redirect to the link URL return Redirect(thisUrl); }