With window.open it is not possible to open only pdf in new tab.
It will open the complete view in new tab.
You need to ues ajax call to the method and based on the condition set the data and open new tab to display the pdf.
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult DownloadPDF()
{
return View();
}
public JsonResult Download()
{
var folderPath = Server.MapPath("~/Files");
var fileCount = Directory.GetFiles(Server.MapPath("~/Files"), "*.pdf");
if (fileCount.Length == 1) // exactly only 1 file
{
string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
embed += "If you are unable to view file, you can download from <a href = \"{0}\">here</a>";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
TempData["Embed"] = string.Format(embed, VirtualPathUtility.ToAbsolute("~/Files/Test.pdf"));
return Json("Exist", JsonRequestBehavior.AllowGet);
}
else if (fileCount.Length > 1) // more than 1 file
{
Process.Start(folderPath);
}
else
{
Process.Start(folderPath);
}
return Json("", JsonRequestBehavior.AllowGet);
}
}
View
Index
<body>
<div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnDownload").click(function () {
$.ajax({
type: "POST",
url: "/Home/Download",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response == "Exist") {
window.open('/Home/DownloadPDF');
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
<input id="btnDownload" type="button" value="Open" />
</div>
</body>
DownloadPDF
<body>
<div>
<%if (TempData["Embed"] != null)
{%>
<%:MvcHtmlString.Create(TempData["Embed"].ToString())%>
<% } %>
</div>
</body>