1

I am writing an action controller in ASP.NET MVC4 which creates a .xls file and returns that FileStreamresult instance. On client side, I have an anchor tag with href attribute set to the above mentioned action controller. I also need to pass some data to the controller based on which controller with query the database and put data in the file. This data is dynamic based on selections made by user on UI. So, I tried passing data using 'data-json' attribute but parameter values are received as null in action method. If I use $.ajax from client side, browser does not show any prompt to download the file.

**Client side code snippet:**
$('#mydiv').append('<a id="Download" href="/MyController/Download">Download</a>');
$('#mydiv').attr('data-json', userFilters);

**Server side code snippet:**
public ActionResult Download(Queryparam filter)
    {
        var stream = new MemoryStream();
        var streamWriter = new StreamWriter(stream);
        var line = "test"; //This is just to keep it simple, actual code uses filter o query db
        streamWriter.WriteLine(line);
        streamWriter.Flush();
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = "TestData.xls",
            Inline = false,
        };
        Response.AppendHeader("Content-Disposition", cd.ToString());
        stream.Seek(0, SeekOrigin.Begin);
        return File(stream, "application/vnd.ms-excel");
    }

userFilters has data in JSON format having same structure as expected by the input parameter in action method. Please share if you have any inputs on how can this be accomplished.

-Thanks

1 Answer 1

2

Firstly href="/MyController/Download" does not call the GetTestFile method (it calls the Download method of MyControllerController).

You can pass the parameters in a the query string, for example href="/MyController/Download?SomeProperty=SomeValue&AnotherProperty=AnotherValue" (your haven't posted the properties of Queryparam). You would need to construct the correct href value using jQuery based on the values of your controls.

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

3 Comments

Thanks. I edited the server side method's name in question. That was a typo. I'll try with query string. Only issue I have is there are currently 8 properties which form Queryparam object and it may increase in future. Query string will become too long. Is there any other alternative?
Yes, there is a limitation on the length of the query string. You could always use a POST.
I was able to successfully pass data using a form and hidden variables. On click of anchor tag, I created a form and posted to server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.