How do I get details from ViewBag into a string for use in FileStreamResult?

175 Views Asked by At

Hello clever coding people, I am working on a MVC project for college, and I am trying to output an invoice, I do not need to view the invoice, just create a downloadable text file. I have been trying to use StringBuilder to get the details from ViewBag, but they are not being written into the file. I am using a @HtmlActionLink to create it from the view. I am sure I am doing something stupid, any advice would be greatly appreciated. Thanks a million.

Method in my Controller:

public FileStreamResult Invoice()
    {
        StringBuilder sb = new StringBuilder("Your Invoice");

        sb.AppendLine(" ");
        sb.AppendLine("Id:"+ @ViewBag.ClientId);
        sb.AppendLine("Name:" + @ViewBag.Name);
        sb.AppendLine("Total:" + @ViewBag.Total);

        var invoiceDetails = sb.ToString();

        var byteArray = Encoding.ASCII.GetBytes(invoiceDetails);
        var stream = new MemoryStream(byteArray);


        return File(stream, "text/plain", "Invoice.txt");

    }
1

There are 1 best solutions below

0
Martin Staufcik On

You could pass a parameter, an ID of the invoce into the action that downloads the invoce.

The action link for downloading the invoice with the ID parameter:

@Html.ActionLink("Download invoice", "Invoice", "MyController", new { id = @Model.InvoiceId }) 

@Model.InvoiceId comes from the model of the view displaying the invoice.

The controller action:

public FileStreamResult Invoice(int id)
{
    ...
}