Question

Using an MVC3 .net controller on the back-end, I am performing an HttpPost to submit a file via the HttpContext.

When the server reads the file, a list of strings is returned with the upload results.

So far, I have been able to get two scenarios working:

1) Return the list of strings as a single, tab-delimited string as a JsonResult

string tabSeparatedMessages = "";

foreach (string message in messageLog)
{
    tabSeparatedMessages = tabSeparatedMessages + message;

    if (message != messageLog[messageLog.Count - 1])
    {
        tabSeparatedMessages = tabSeparatedMessages + '\n';
    }
}
return this.Json(new
{
    success = true,
    total = messageLog.Count,
    data = tabSeparatedMessages
}, "text/html", JsonRequestBehavior.AllowGet);

2) Return the list of strings in a text file as an ActionResult

string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".txt";

using (StreamWriter writer = new StreamWriter(fileName))
{
    foreach (string message in messageLog)
    {
        writer.WriteLine(message);
    }
}

return File(fileName, "text/plain", "UPLOAD_RESULTS.txt");

My problem is that I want elements from each of these methods but am having difficulty combining the two. I want the JsonResult so that I can return a boolean 'success' value to release a modal, waiting message on the client. I want the ActionResult so that the client can simply download a file instead of parsing the list of strings into the GUI components.

Is there a way to return a text file to be downloaded as part of the JsonResult or return Json data with the ActionResult?

Thank you for reading

Was it helpful?

Solution

Unfortunately you can only return one result type at a time. If I were you and I really needed that upload_results.txt to be downloaded to the client I would have a parameter in my json result that is a reference to the file on the server.

So the client first get the response that the upload was successful and you hide the modal dialog, then with javascript you make another request for the upload_results.txt file.

OTHER TIPS

I agree with above, send down the JSON and store the file temporarily on the webserver. Have the path to this file in the JSON and then just do a GET

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top