How to view PDF files within browser without downloading them in MVC

In this article we will learn how to show pdf file in mvc on browser.
So we will call a method with  get and post operation in controller
Get method simply return the view and post operation returns HTML string is set into a TempData and redirected to Index action.
Controller :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ViewPDF()
        {
            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("~/Neeraj-Code-Solutions.pdf"));

            return RedirectToAction("Index");
        }

    }
}
View:-

@{
    Layout = null;
}

<!DOCTYPE html>



<html>
<head>
    <meta name="viewport" content="width=device-width" />
 
</head>
<body>
    @using (Html.BeginForm("ViewPDF", "Home", FormMethod.Post))
    {
        <a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
        <hr />

        @Html.Raw(TempData["Embed"])
    }
</body>

</html>


How to view PDF files within browser without downloading them in MVC How to view PDF files within browser without downloading them in MVC Reviewed by NEERAJ SRIVASTAVA on 10:29:00 PM Rating: 5

No comments:

Powered by Blogger.