asp.net-mvc-4controllerredirecttoactionfileresult

First run FileResult to download file, then RedirectToAction


This will send an email when a button gets pushed. However I am trying to call the FileResult, SaveDocument, to download a file right before redirecting back to the button page.

I am using a hardcoded file for now to download for the sake of testing. I can run the SaveDocument() result using a test button. I can't send an email, run the SaveDocument Action and then redirect.

[HttpGet]
public ActionResult send(int thisbatch, string listofpositives)
{
    MailMessage mail = new MailMessage();

    SmtpClient smtpServer = new SmtpClient("smtperServer");
    smtpServer.Port = 25; // Gmail works on this port
    smtpServer.EnableSsl = false;
    mail.From = new MailAddress("xxxe@xxx.com");
    mail.To.Add("xxxe@xxx.com");
    mail.Subject = "Batch Closed";
    mail.Body="some info stuff here";

    smtpServer.Send(mail);

    SaveDocument();

    return RedirectToAction("AddColiform");

}

//THIS WORKS BY ITSELF CALLED FROM A BUTTON
    public FileResult SaveDocument()
    {
        string filePath = Server.MapPath("~/XML_positives/Test1.xml");
        string contentType = "text/xml";

        return File(filePath, contentType, "Test1.xml");

    }

Solution

  • Well, no solution was found (so far) to download a file and RedirectToAction back to the initial page in the same ActionResult. If someone can come up with a better answer I will take this one off.

    So based on contents of string "listofpositives" I call a new View "Has Positives" with 2 buttons: One calls the FileResult Action and one redirects back to where everything started (this is desired). A lot clunkier than just popping up a File Save As dialog and then moving on automatically. But I need to build something and move on. I feel sorry for my users. oh well.

    Here is the code after I send an email and return to desired view:

    if (listofpositives == "")
    {
    
        return RedirectToAction("AddColiform");
    }
    else
    {
        return RedirectToAction("HasPositives",new { thisbatch=thisbatch, listofpositives=listofpositives});
    }
    

    Here is the code for the whole extra view:

    @{
        ViewBag.Title ="HasPositives" ; 
    }
    
    <h2>HasPositives</h2>
    
    
    <p>Batch: @ViewData["batchid"] </p>
    <p>Postives: @ViewData["listofpositives"]</p>
    
    <br /><br />
    
    Process your XML file using XMLSampling<br /><br /><br />
    
    &nbsp;&nbsp;&nbsp;&nbsp;
    
    <button onclick="location.href='@Url.Action("SaveDocument", "Home")';return false;">Download Positive XML File</button>
    
    &nbsp;&nbsp;&nbsp;&nbsp;
    <button onclick="location.href='@Url.Action("AddColiform", "Home")';return false;">Done</button>