0

私のコントローラーには、FileStreamResultを返すGenerateDocumentメソッドがあります。

私の見解では、私は単にそのように新しいものを開くjavascriptを持っています。window.open('/ controller / GenerateDocument /?id = blah');

GenerateDocumentメソッドが必要なのは次のとおりです。1。ドキュメントをエラーなしで作成/フェッチできる場合はPDFを返し、2。エラーがある場合は新しいページ/ビューを返します。

コントローラコードは次のとおりです。

    public FileStreamResult GenerateDocument(int id)
    {
        string errorResult = string.Empty;

        try
        {
            DocumentDetail documentDetail =
                 DocumentGenerator.GenerateAgreements(id, DcmDocumentEntityType.Sponsor, GetAuthUser());

            if (documentDetail == null) return null;

            Stream stream = DocumentGenerator.RetrieveFile(documentDetail);

            return new FileStreamResult(stream, "application/pdf");
        }
        catch (Exception ex)
        {
            errorResult = FormatException(ex);
            Trace.TraceError(errorResult);
        }

        //ViewBag.Error = HttpUtility.HtmlEncode(errorResult).Replace("\n", "<br />");

        //return View("DocGenerationError");
        return null;
    }

ActionResultを使用してエラーが発生した場合にビューを返すようにしましたが、このスレッドのコメントで述べたように、ページjavascriptでは、window.open(url)が正しく機能しませんでした。

ビューコードは次のとおりです。

  $('#ActionMenu').change(function() {
      var action = $(this).val();

      switch (action) {            
      case 'Generate Sponsor Agreement':
          window.open('/Sponsor/GenerateDocument/?id=@(Model.SponsorID)');
          break;

      other cases

      default:
      }
  });

注:上記のコントローラーコードは機能します。ActionResultを返すように切り替えて、例外処理のコメントを外すと、機能しなくなります。

4

2 に答える 2

3

あなたの問題を理解しているかどうかわかりません。これを行うことの何が問題になっていますか?

public ActionResult GenerateDocument() {
     ..... // Do code
     if (errors)
         return View(errorModel);
     return new FileStreamResult(...); // your pdf file
}
于 2012-10-04T15:56:51.740 に答える
2

これは、FilePathResultを返すController.Fileメソッドを使用するだけで実行できます。いくつかのオーバーロードがありますが、ここに例があります:

return File(streamreader.ReadToEnd(), "text/plain", "Result.PDF");

FilePathResultはActionResultから継承するため、アクションの戻りタイプを変更する必要はありません。エラーが発生した場合は、これを処理するためにビューを返すことができます。

于 2012-10-04T15:57:42.090 に答える