views:

1406

answers:

3

Consider the need to return a plain-text file from a controller method back to the caller. The idea is to have the file downloaded, rather than viewed as plaintext in the browser.

I have the following method, and it works as expected. The file is presented to the browser for download, and the file is populated with the string.

I'd like to look for a 'more correct' implementation of this method, as I am not 100% comfortable with the void return type.

public void ViewHL7(int id)
{
    string someLongTextForDownload = "ABC123";

    Response.Clear(); 
    Response.ContentType = "text/plain";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.hl7", id.ToString()));
    Response.Write(someLongTextForDownload);
    Response.End();
}
+3  A: 

You'll want to return a FileContentResult from your method.

Chris Missal
+13  A: 

Use the File method on the controller class to return a FileResult

public ActionResult ViewHL7( int id )
{
    ...

    return File( Encoding.UTF8.GetBytes( someLongTextForDownLoad ),
                 "text/plain",
                  string.Format( "{0}.hl7", id ) );
}
tvanfosson
Tks tvanfosson.Your answer helped me so much.
Renato Bezerra
A: 

That's really good and I am also using the same. But I do have a problem. In addition to returning this file, once that is successful, I want to Redirect to another ActionResult!! How to achieve that??

Thanks a lot for any help..

Pawan