1

I'm pretty new to mvc and jQuery... and to web development in general really. I recently took over control of a site designed by a developer that we had to let go and the treeview control he had used needed to be changed for reasons that I won't get into here. But basically I need to be able to have resources be download on the click event of a node in the treeview. I know how to handle the event but I can't figure out how to make the call to my mvc controller through jquery. The path to the controller function I need to call to download the resource is /Resources/DownloadResource. Here's the code for it:

        public ActionResult DownloadResource(string id)
        {
            var resource =
                _resourceService.GetResourceQuery(new Specification<Resource>(r => r.ResourceId == new Guid(id))).FirstOrDefault();

        return new BinaryResult
        {
            FileName = resource.FileName,
            ContentType = string.Format("application/{0}", Path.GetExtension(resource.FileName)).Replace(".", ""),
            IsAttachment = true,
            Data = System.IO.File.ReadAllBytes(resource.FilePath)
        };
    }

I have tried something like $.post("/Resources/DownloadResourceLink", { id: value }); and when I step through, everything is getting the correct values, but no download. Any help would definitely be appreciated!

4 Answers 4

3

To trigger the download from the browser, you need to use a synchronous way not ajax.

Look at this question: Downloading a file onto client in ASP.NET MVC application using JQuery

Sign up to request clarification or add additional context in comments.

Comments

2
<script type="text/javascript">

    $(document).keypress(function (e) 
    {
        if (e.which == 13) 
        {
             location.href = '@Url.Action("ActionName", "Controllername")';
        }
    });

</script>

Comments

0

Try looking at This Basically you are just calling the MVC action address as the url property of your ajax function.

Comments

0

The problem may be how you are passing in the id. In my experience, I have to append the data into the url (/action/controller/id route)

$.post("/Resources/DownloadResourceLink/" + value);

If that doesn't work, I'd make sure the content type the call is expecting is correct for the download type.

If that still doesn't do it, then the issue may be the post.

I recommend you take a look at $.ajax(). The default is a get, which you may need for a download. I don't know what the content type needs to be (you should be able to infer that from the action method), but your call would look something like this.

$.ajax({
    url: '/Resources/DownloadResourceLink',
    params: { id }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.