7

I am working with MVC3 c# 4.0.

I have created a partial view.

I have a button on my page, when I click this button I want to be able to load the partial view in to a modal popup. I presume the best way to do this is via javascript - I am using jQuery already in the application.

Any pointers as to how I could do this?

amateur
  • 43,371
  • 65
  • 192
  • 320

1 Answers1

11

You could use jQuery UI dialog.

So you start by writing a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Modal()
    {
        return PartialView();
    }
}

then a Modal.cshtml partial that will contain the partial markup that you want to display in the modal:

<div>This is the partial view</div>

and an Index.cshtml view containing the button which will show the partial into a modal when clicked:

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('.modal').click(function () {
            $('<div/>').appendTo('body').dialog({
                close: function (event, ui) {
                    dialog.remove();
                },
                modal: true
            }).load(this.href, {});

            return false;            
        });
    });
</script>

@Html.ActionLink("show modal", "modal", null, new { @class = "modal" })

Obviously in this example I have put the directly scripts into the Index view but in a real application those scripts will go into separate javascript file.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thank you very much for this example it helps alot. One further question, I have integrated in MVC3 in to my web forms application. So the control that triggers the modal is on the web forms. I don't think I can use @Html.ActionLink in web forms, is there an alternative? – amateur May 23 '12 at 22:46
  • Of course that there is an alternative. All that the `Html.ActionLink` helper generates is an `` tag. So you could generate this markup in your web forms application. – Darin Dimitrov May 24 '12 at 05:55
  • 1
    Hello Darin, i have tried using this like http://stackoverflow.com/questions/15876993/display-partialview-as-popup but i still just get a new page. Any idea? – Tim Apr 08 '13 at 11:14
  • 1
    I hate css & now this answer too..killed a lot of my time. If anyone else is having trouble please use https://www.codeproject.com/Tips/826002/Bootstrap-Modal-Dialog-Loading-Content-from-MVC-Pa to understand things better – madasu naga Jul 09 '17 at 23:46