Display File Content in Popup Window in MVC


Introduction

This article demonstrates how to display a file (Image, PDF, Notepad etc.) in popup window using MVC. This article demonstrates without taking image tag in view for display image in view. This article takes three controls in view for completing the task. This demonstration is browsing a file from client computer and displays that file in popup window in view by button click.




To get the image or other file opened in the popup window, you need an extra action in your controller for attaching your file with request.

Getting Started

Open your visual studio create a MVC Project, Create a new controller in your application and create a view for your application by right clicking on the index action. Write down codes to open your view in the index action. In the Index view take a file control and one button for browsing and display file in image.

 string FilePath= @Model.FilePath.Replace("\\", "@");  
 <input type="file" />   <input type="button" value="Open" onclick="viewdoc('@Model.FilePath','@Model.FileName')"/>  
In the above code I have replaces ''\\'' with '@' because it violets the routing rule.

Create a JavaScript function in your view in the script section for sending request to action controller and displaying file in the pop window. see the code below

 function viewdoc(FilePath,FileName)  
 {  
     window.open('/ControllerName/ActionName?FilePath=' + FilePath+ '&FileName=' + FileName,"PopupWindow", 'width=600px,height=600px,top=150,left=250');  
 }  





Add another action to your controller for opening your file. In this action we will write some IO codes to read your file and send your file to view with response. See below code example

 public ActionResult ViewDoc(string Filepath, string Filename)  
  {  
         Filepath= Filepath.Replace("@", "/");  
         string contentType = MimeMapping.GetMimeMapping(Filepath);  
         if (System.IO.File.Exists(Filepath))  
         {  
            string attachment = string.Format("inline; filename={0}", Filename);  
            Response.Clear();  
            Response.AddHeader("content-disposition", attachment);  
            Response.ContentType = contentType;  
            Response.WriteFile(path);  
            Response.Flush();  
            Response.End();  
            return View();  
        }  
         else  
          return HttpNotFound();  
 }  

Summary

This above discussion is the details about how to display any file in the popup window using MVC technology. here we have done some server side code and client side code as well, Hope you have understood the concept, if this makes helpful to you please give a comment.

Thanks