VansFannel
VansFannel

Reputation: 45921

Keep it on the same page if there isn't any file to download

I'm developing an ASP.NET MVC 5 app with C# and .NET Framework 4.5.1.

I want to return a XML to user when it selects an order in a SELECT.

This is the view:

@model IEnumerable<Models.ProductionOrder>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @using (@Html.BeginForm("GetXML", "Orders"))
        {
            <p>
                @Html.DropDownList("productionOrderId", 
                                    new SelectList(Model, "Id", "OrderNumber"),
                                    "Orders",
                                    new {id = "OrdersSelect", onchange = "submit();"})
            </p>
        }
    </div>
</body>
</html>

And the GetXML method is this:

public FileContentResult GetXML(long productionOrderId)
{
    ProductionOrderReport poReport = null;

    poReport = new ProductionOrderReport(m_Repository, m_AggRepo, m_AggChildsRepo);

    // Get the XML document for this Production Order.
    XDocument doc = poReport.GenerateXMLReport(productionOrderId);

    if (doc != null)
    {
        // Convert it to string.
        StringWriter writer = new Utf8StringWriter();
        doc.Save(writer, SaveOptions.None);

        // Convert the string to bytes.
        byte[] bytes = Encoding.UTF8.GetBytes(writer.ToString());

        return File(bytes, "application/xml", "report.xml");
    }
    else
        return null;
}

Sometimes the XML file returned can be null, and on those cases I get a empty screen on my browser.

How can I do to keep it the same page if the file is null?

I have tested this: instead of return null on GetXML method, I want to return a View (Index.cshtml), but I can't because GetXML returns FileContentResult.

Upvotes: 0

Views: 262

Answers (1)

Siva Gopal
Siva Gopal

Reputation: 3502

If your application permits to do the following changes, you can try the following:

public ActionResult GetXML(long productionOrderId) //Changed Return Type
{
    ProductionOrderReport poReport = null;

    poReport = new ProductionOrderReport(m_Repository, m_AggRepo, m_AggChildsRepo);

    // Get the XML document for this Production Order.
    XDocument doc = poReport.GenerateXMLReport(productionOrderId);

    if (doc != null)
    {
        // Convert it to string.
        StringWriter writer = new Utf8StringWriter();
        doc.Save(writer, SaveOptions.None);

        // Convert the string to bytes.
        byte[] bytes = Encoding.UTF8.GetBytes(writer.ToString());

        return File(bytes, "application/xml", "report.xml");
    }
    else
        return RedirectToAction("ViewName","ControllerName"); //Instead of returning null, you can redirect back to the GET action of the original view.
}

Hope this help you.

Upvotes: 1

Related Questions