How to download a file using web api in ASP.NET MVC 4 and jquery

后端 未结 1 767
谎友^
谎友^ 2020-12-15 22:39

I am new to using ASP.NET MVC 4 with Web Api.

I want to allow user to download a file, this file I will be creating on the server side. For creating the file I have

相关标签:
1条回答
  • 2020-12-15 23:08

    You can do something like this inside the view where you want to use jquery. I assume the name of the controller is ExportController. You also have to break down the model variables, or alternatively collect the model inside HttpResponseMessage PostExportData(SomeModel model) via some other way.

    html:

    <a class="export">export</a>
    

    javascript:

    <script>
    $('a.export').click(function(e) {
        e.preventDefault();  //stop the browser from following
        window.location.href = '@Url.Action('Export', 'ExportController', new { property = model.property, property = model.property2 })';
    });
    </script>
    

    To use POST

    function UpdateForm(modelObject) {
       if ($('#hidden-form').length < 1)
       {
           $('<form>').attr({
               method: 'POST',
               id: 'hidden-form',
               action: '@Url.Action('Export', 'Export')'
           }).appendTo('body');
       }
       $('#hidden-form').html('');
       for(var propertyName in modelObject) {
           $('<input>').attr({
                type: 'hidden',
                id: propertyName,
                name: propertyName,
                value: modelObject[propertyName]
           }).appendTo('#hidden-form');
        }
    }
    
    $('a.export').click(function(e) {
        e.preventDefault();
        var modelObject = { property1 : "property1" };
        UpdateForm(modelObject);
        $('#hidden-form').submit();
    });
    

    Then you can just post #hidden-form via js which will trigger the file download

    Update: This is a full example for posting, and its not checked for typos etc so debug any minor errors.

    0 讨论(0)
提交回复
热议问题