Open a view as a pop up

2019-01-23 18:10发布

问题:

Controller.cs is:

 public ActionResult ViewRequest(int id)
        {
            Job job = Jobs.GetJob(id);

            return View(job);
        }

It's view is:

@model model.Job
<fieldset>
    <legend>Job</legend>


    <div class="display-label">Name</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>

</fieldset>
    @Html.ActionLink("Download", "Download", new { id = model.Id }) |

How do I open it as a model pop up

回答1:

Add a class to the link:

@Html.ActionLink("Download", "Download", new { id = model.Id }, 
                                         new{ @class = "dialog"} )

And add this script somewhere:

<script type="text/javascript">
    $(function (){
        $('a.dialog').click(function() {
            var url = $(this).attr('href');
            var dialog = $('<div style="display:none"></div>').appendTo('body');
            dialog.load(url, {}, 
                function (responseText, textStatus, XMLHttpRequest) {
                dialog.dialog({
                    close: function(event, ui) {
                        dialog.remove();
                    }
                });
            });
            return false;
        });
    });
</script>

Required CSS/JS

  • jQuery UI: https://jqueryui.com/


回答2:

You could append the target="_blank" HTML attribute to the anchor if you want the url to be opened in a new browser window:

@Html.ActionLink(
    "view request in a new window", 
    "ViewRequest", 
    new { id = model.Id }, 
    new { target = "_blank" }
)

Or if you want to open it in a new modal window you could use the jQuery UI Dialog widget you could unobtrusively AJAXify this link (after applying it an unique id):

@Html.ActionLink(
    "view request in a new window", 
    "ViewRequest", 
    new { id = model.Id }, 
    new { id = "linkId" }
)

and then in a separate javascript file:

$(function() {
    $('#linkId').click(function() {
        $.get(this.href, function(result) {  
            $(result).dialog();
        });
        return false;
    });
});

or if you want to open the dialog immediately when the link is clicked and provide a small feedback while the AJAX call executes:

$(function() {
    $('#linkId').click(function() {
        $('<div>Loading ...</div>').load(this.href).dialog();
        return false;
    });
});