Javascript function to open a file not getting called

884 views Asked by At

i am having problem in calling javascript function
I want to open a file on click of a link.

Here is my code:

<script language="javascript" type="text/javascript">
var refViewer = null;

function OpenViewerWindow(image) {
    return window.open(image, "Viewer", "height=400px,width=550px,menubar=no,scrollbars=yes ,resizable=yes,top=100px,left=234px");

}


function openViewer(image) {

    if (refViewer != null) {
        if (refViewer.closed == false) {
            refViewer.close();
            refViewer = OpenViewerWindow(image);
        }
        else refViewer = OpenViewerWindow(image);
    }
    else
        refViewer = OpenViewerWindow(image);
}   


</script>

<a onclick=javascript:openViewer(@ViewBag.path)><img src="pic.jpg"/></a>

and the in the controller:

 public ActionResult ActivityPosting(int HobbyDetailID)
    {
string filepath = Server.MapPath("~/ePortfolio/PortFolioContent/" + HobbyDetailID + "/ReferenceMaterial/" + item.FilePath);
 ViewBag.path = filepath;
    return view();
   }

The problem is the javascript function does not get called.Please help me

2

There are 2 answers

7
Mathew Thompson On

Try this instead in your JavaScript OpenViewerWindow function (you need to use the file:// protocol:

return window.open("file://" + image, "Viewer", "height=400px,width=550px,menubar=no,scrollbars=yes   ,resizable=yes,top=100px,left=234px")
3
Darin Dimitrov On

Make sure you pass a string:

<a onclick=javascript:openViewer('@ViewBag.path')><img src="pic.jpg"/></a>

Notice the single quotes. Or even better use Json.Encode to ensure proper encoding of the value that is passed to your openViewer javascript function:

<a onclick="javascript:openViewer(@Html.Raw(Json.Encode(ViewBag.path)))"><img src="pic.jpg"/></a>

Also there's another issue with your code. You use Server.MapPath to calculate the url but this method returns the absolute path to the file on the server. The client obviously cannot access it with an absolute path. You should pass an url using the Url.Content helper:

public ActionResult ActivityPosting(int HobbyDetailID)
{
    string filepath = Url.Content("~/ePortfolio/PortFolioContent/" + HobbyDetailID + "/ReferenceMaterial/" + item.FilePath");
    ViewBag.path = filepath;
    return View();
}