2015-02-04 2 views
0

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이 될 수 반환하고, 이러한 경우에 나는에 빈 화면을 얻을 내 브라우저.

파일이 null 인 경우 동일한 페이지로 유지하려면 어떻게해야합니까?

나는 이것을 테스트했습니다 : GetXML 메서드에서 null을 반환하는 대신 뷰를 반환하고 싶지만 GetXMLFileContentResult을 반환하기 때문에 볼 수 없습니다. 응용 프로그램 허용이 다음과 같이 변경을 할 경우

답변

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

희망이 당신을 도울.

+0

감사합니다. 그것은 완벽하게 작동합니다. – VansFannel

+0

@VansFannel 건배 !! :) –

관련 문제