Often you want to hide the physical location of downloadable files on a site. With ASP.NET web forms this could easily be achieved using a Http Handler, grabbing the file from disk (or perhaps a database) and then adding the binary content to the output stream.
In ASP.NET MVC things get even easier with the File method. I had to create a HTML wireframe for a client that involved a downloads page so thought I would add a couple of files to download.
My controller action:
public ActionResult Get(string id)
{
string file = Server.MapPath("~/Content/resources/" + id);
if (System.IO.File.Exists(file))
return File("~/Content/Resources/" + id, "application/pdf", id);
else
return RedirectToAction("Index");
}
In a real life application you would probably not hard code the paths or mime types but you get the idea.
So to request a file I can call:
http://localhost:54215/Resources/get/myfile.pdf
This may look like it is looking for a file “myfile.pdf” in the “get” directory, but it is actually passing the file name as an argument to the Get action on the Resources controller.
Something I wanted to add to my resource list was a hover effect on the div container for each resource and allow the user to click anywhere on the container to download the file.
Since IE does not support the pseudo hover class on anything other than links I knew I would need to use a bit of JavaScript. I made each title a hyperlink so it still works if JavaScript is disabled.
<div class="file pdf"> <div class="details"> <%=Html.ActionLink("T15/T25 Gen Pac", "Get", new{ id= "s40-45.pdf"}) %> <p> Nulla facilisi. Morbi augue magna, accumsan eu bibendum malesuada, varius eget felis. Nunc molestie metus vitae metus lobortis vulputate. </p> </div> </div>
We can achieve the above behaviours with JavaScript, or specifically, using everyone’s favourite library, jQuery:
$(function() {
$(".file").hover(function() { $(this).addClass("resourceHover"); },
function() { $(this).removeClass("resourceHover"); })
.click(function() {
var link = $("a", this);
if (link.length != 0)
window.location = link.attr("href");
});
});
The hover effect is achieved using the jQuery addClass and removeClass functions. To download the file I have assigned a click function for the container div that retrieves the url of the child hyperlink element and sets window.location.
The result:
jQuery and ASP.NET MVC – making my life easier.