Reputation: 10552
I am needing to be able to call a javascript function from my MVC 5 controller. However, I am currently using a return in my controller and from what I gathered, you are unable to return 2 things...
The code I currently have is this:
public async Task<FileResult> exportTempBom()
{
bool x = await checkExcelFile();
string originalDirectory = Path.Combine(new DirectoryInfo(string.Format("{0}App_Data\\", Server.MapPath(@"\"))).ToString(), "downloads");
byte[] fileBytes = System.IO.File.ReadAllBytes(originalDirectory + "\\BomTemp.xlsx");
return File(fileBytes, "application/vnd.ms-excel", "BomTemplate.xlsx");
}
....more code here....
<iframe name="_frameDownload" id="_frameDownload" src="" style="width: 0px; height: 0px; display: none;"></iframe>
As you can see in the code above, I'm already sending back the excel file that the user has requested to download. However, I am needing to call a javascript function either before or after the return of the file to the user.
What I am needing to do is call loadingTheOverlay(false); from the controller AFTER the file has began to download. Calling this will take the overlay off of the page so that the user can continue to navigate the site.
The checkExcelFile() is where I check the excel file that they are about to download to make sure its up to date. If its not then it updates the file before it begins the download. That is why I am in need of the overlay so the user knows why its taking longer than normal to download the excel file.
I am calling that controller with this on the razor page:
<ul class="dropdown-menu">
<li>@Html.ActionLink("Download BOM Template", "exportTempBom", "Templates")</li>
<li>@Html.ActionLink("Download Inventory Template", "exportTempInventory", "Templates", null, new {
onclick = "loadingTheOverlay(true);",
target = "_frameDownload"
})</li>
</ul>
Is there any MVC code that would do what the original ASP.net could do?
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);
Upvotes: 0
Views: 972
Reputation: 218852
You can execute a javascript method before making the call to the action method.
You need to handle the click event on the link, prevent the default behavior, call your custom js function and then call the other action method.
@Html.ActionLink("Download BOM Template", "exportTempBom", "Templates",
null,new { id="downloadLink"})
The above code will render an anchor tag with id downloadLink
.
Now the javascript to handle the click
event of this specific link
$(function(){
$("#downloadLink").click(function(e){
e.preventDefault();
myCustomMethod();
window.location.href=$(this).attr("href");
});
});
You should not think about returning a javascript function/string literal for the js function from your server action method. That pattern is just bad!!!!
Upvotes: 1