如果没有要下载的文件,请将其保留在同一页面上

时间:2015-02-04 10:22:38

标签: c# asp.net asp.net-mvc

我正在使用C#和.NET Framework 4.5.1开发ASP.NET MVC 5应用程序。

我想在SELECT选择订单时将XML返回给用户。

这是观点:

@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>

GetXML方法是这样的:

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;
}

有时返回的XML文件可以为null,在这些情况下,我的浏览器会出现空白屏幕。

如果文件为空,我该如何保持同一页面?

我测试了这个:我不想在GetXML方法上返回null,而是想返回一个视图(Index.cshtml),但我不能,因为GetXML返回FileContentResult }。

1 个答案:

答案 0 :(得分:1)

如果您的应用程序允许进行以下更改,您可以尝试以下操作:

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.
}

希望这对你有所帮助。