简体   繁体   中英

How to conditionally open a new window/tab from an anchor tag?

I have the following code that will open a new tab/window and display the contents of a file based on a user clicking a button in a grid.

$(myButton).attr('href', '/MyController/GetDoc?Field1=' + dataItem.data1 + '&Field2=' + dataItem.data2);    
$(myButton).attr('target', '_blank');

In the controller I return

return new FileContentResult(Convert.FromBase64String(myDoc), "application/pdf");

Everything works fine if I have a document.

How can I prevent the event from occurring if the controller method errors out or no document was found?

UPDATE:

$(function () {

    $(".myButtonClass").each(function () {
        var button = $(this);
        var docUrl = '';

        button.attr('target', '_blank');
        checkDocumentUrl(button, docUrl);
    });

});

In my button click method:

var myButton = $(e.currentTarget).closest(".myButtonClass");
$(myButton).attr('href', '/MyContoller/GetDoc?Field1=' + dataItem.data1+ '&Field2=' + dataItem.data2);   

Before the button is clicked, request the document from the server. If that fails, the document does not exist, and you can disable the button through JavaScript.

Your controller should check if the document exists, and return HTTP 404 if it does not.

 //Example data only. Each button presumably has its own data. var dataItem = { data1: 'foo', data2: 'bar' }; $(document).ready(function() { //Check the url for each button $('.myButton').each(function() { var button = $(this); var docUrl = '/MyController/GetDoc?Field1=' + dataItem.data1 + '&Field2=' + dataItem.data2; button.attr('href', docUrl); button.attr('target', '_blank'); checkDocumentUrl(button, docUrl); }); function checkDocumentUrl(button, docUrl) { //Make a request for the document $.ajax({ method: 'HEAD', url: docUrl, error: function() { //If request fails, document does not exist handleInvalidDocument(button, docUrl); } }); } function handleInvalidDocument(button, docUrl) { button.on('click', function(e) { //Prevent the link from opening a new tab e.preventDefault(); alert('Sorry, no document available at ' + docUrl); }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="myButton">My Button</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM