title: open file from ajax responce in mvc c#
body: <p>I want to open file from Ajax response. here is the code. Here Ajax call response contain PDF file.</p>
  
  <p>I want to open file in new tab of browser.here i am using mvc framework.</p>
  
  <pre><code>function ViewPDF(key){
  $.ajax({
              url: '@Url.Action("OpenDocument", "DocumentApproveUser")',
              type: "POST",
              data: { "key": key},
              async: true,
              cache: false,
              success: function (data, status, xhr) {
                  alert(data);
                  window.open(data);
                  if (xhr.getResponseHeader("Forcefullylogin") == "true") {
                      var url = "/Login/Login";
                      window.location.href = url;
                  }
                  else {
                  }
              },
              error: function (error) {
                  $("#divLoading").hide();
                  if (error.getResponseHeader("Forcefullylogin") == true") {
                      var url = '@Url.Action("Login", "Login")';
                      window.location.href = url;
                  }
                  else {
                      alert('Something went wrong in system.Please try again later!or contact to system administrator.');
                  }
              }
          });
      }
  </code></pre>
  
  <p>Server Code :
  see below is code of my controller. this code return pdf file as ajax response.
  I want to open that response in my browser.  </p>
  
  <pre><code>[HttpPost]
      public ActionResult OpenDocument(string key)
      {
          try
          {
              int Id = 0;
              try
              {
                  byte[] data = Convert.FromBase64String(key);
                  string decodedString = System.Text.Encoding.UTF8.GetString(data);
  
                  if (!(String.IsNullOrEmpty(decodedString)))
                      Id = Convert.ToInt32(decodedString);
              }
              catch (Exception ex)
              {
                  ViewBag.ErrorName = "An error occured while opening document.";
                  base.ErrorLogger.Error("***OpenDocument***", ex);
                  return null;
              }
              DocumentApproveViewModel vm = new DocumentApproveViewModel();
              vm.DocumentsApprovalModel = DocumentApproveViewModel.GetDocTransactionModelList(_repo.GetAll());
              DocumentApprovalModel lst;
  
              lst = (from x in vm.DocumentsApprovalModel where x.Id.Equals(Id) select x).FirstOrDefault();
              base.Logger.InfoFormat("User : '{0}' going to access pdf document at {1} ", SessionFactory.CurrentUser.Name, System.DateTime.Now);
              /////////////////////////////////////////////////////////////////////
              ICollection&lt;PasswordManagementViewModel&gt; passwordList = null;
              PasswordManagementViewModel password = null;
              passwordList = PasswordManagementViewModel.GetSystemEncryptionKeyList(_encryption.GetAll());
              password = passwordList.OrderByDescending(x =&gt; x.CreatedDateTime).FirstOrDefault();
              string decryptPassword = Base64EncodeDecode.Decrypt(password.EncryptionKey, true);
              /////////////////////////////////////////////////////////////////////
              // Inhariting Logic from PDFSharpUtil Class.
              byte[] PdfFileByte = _docSecurity.OpenPdfFile(lst.File, decryptPassword, SessionFactory.CurrentUser.EncryptionKey, SessionFactory.CurrentUser.Name, lst.DocumentTransactionName, false, SessionFactory.PdfViewCount);
  
              /// Added logic for adding data into Document History ///
              DocumentHistory objDocumentHistory = new DocumentHistory();
              objDocumentHistory.SentTo = null;
              objDocumentHistory.Timestamp = DateTime.UtcNow;
              objDocumentHistory.ActionPerformedBy = SessionFactory.CurrentUser.Id;
              objDocumentHistory.Action = EDocumentAction.View;
              objDocumentHistory.DocumentId = Id;
              _docHistoryRepo.Add(objDocumentHistory);
              //Increment view count not to ask password from second attempt to open PDF file
              SessionFactory.PdfViewCount++;
              return File(PdfFileByte, "application/pdf");
          }
          catch (Exception ex)
          {
              ViewBag.ErrorName = "An error occured while opening Document";
              base.ErrorLogger.Error("***OpenDocument :: DocumentView***", ex);
          }
          return null;
      }
  </code></pre>