0

I display a table with data on the page and then when user clicks Export I put the data in the excel file. Now I want to open this file so that user can save it or just view it. This is the code I have. It prompts the user to save a file but that file is the whole page!! WHat is wrong here?

   string filename = filePath.Substring(12);
                        System.IO.File.Copy(filePath, "C:/Work/MCTestSuiteCertificate/TS.ToDoViewer/Content/" + filename, true);
                        Response.Clear();
                        Response.ContentType = @"application\xls";
                       // FileInfo file = new FileInfo(Server.MapPath("~/Content/" + filename));
                        Response.AddHeader("Filename", filename);
                        Response.ContentType = "application/xls";
                        Response.TransmitFile("C:/Work/MCTestSuiteCertificate/TS.ToDoViewer/Content/" + filename);
                        //Response.WriteFile(file.FullName);
                        Response.Flush();

1 Answer 1

2

Use File method (which returns FileResult). You should not work directly with Response in MVC application.

public ActionResult YourAction()
{
    ...
    string filename = filePath.Substring(12);
    return File(Path.Combine(@"C:\Work\MCTestSuiteCertificate\TS.ToDoViewer\Content", filename), "application/xls");
}

PS Also please note use of Path.Combine instead of string concatenation.

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

2 Comments

@Serg When I do this I get no error - BUT excel is not opened either. I call it with: ** <input type="submit" value="Report" onclick="location.href='@Url.Action("YourAction", "Employee" )'" />**
Check the HTTP calls between client and server to find out where the issue lies.

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.