简体   繁体   中英

Call mvc controller with jQuery

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!

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

<script type="text/javascript">

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

</script>

尝试看一下基本上,您只是将MVC操作地址称为ajax函数的url属性。

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 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM