user646751
user646751

Reputation: 51

How to open a jquery dialog in MVC

I have an aspx page and UserControl [ it contains a button,textbox ] and userControl is added onto aspx page

So When i click button in aspx page it should make a Jquery ajax call to the Controller to open a dialog .

how can i do this....in this we have to make a call to controller

Upvotes: 0

Views: 5335

Answers (2)

fgpx78
fgpx78

Reputation: 1280

It's pretty easy - you create a partialview that will be the actual dialog content (let's call it MyDialogPV) - you create a method in the controller that returns the PartialView (GetMyDialogPV) - you use ajax to call the PartialView and render it at runtime as a dialog (in the example I use the JqueryUI plugin).

Controller code:

public PartialViewResult GetMyDialogPV() { 
        //do some stuff, probably you'll need to set up a model given input parameters
        ViewBag.Text = "This is my dialog text, opened at " + DateTime.Now.ToLongTimeString();
        //retunr the partialview rendered
        return PartialView("MyDialogPV");
    }

The partial view for the dialog:

<div>Title</div>
<div>
    @ViewBag.Text
</div>

The parent page code:

@{ViewBag.Title = "Home Page";}
<script>
$(document).ready(function () {
    $('#lod').click(function () { //click event of the link            
        //load the dialog via ajax
        $.ajax({
            url: '@(Url.Action("GetMyDialogPV"))',
            type: "GET",
            dataType: "html",
            cache: false,
            success: function (data) {
                $('#myDialogContainer').html(data); //write the dialog content into the diaog container
                $("#myDialogContainer").dialog({ //dialogize it with JqueryUI
                    autoOpen: false,
                    height: 400,
                    width: 450,
                    modal: true,
                    buttons: {
                        "Chiudi": function () { $(this).dialog("close"); }
                    },
                    close: function () { }
                });
                $("#myDialogContainer").dialog("open"); //open it!
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Error');
            }
        });
    });
});
</script>
<a id="lod">Load And Open Dialog</a>
<div id='myDialogContainer' style="background:red">this is the container for the html retrieved by the controller action GetMyDialogPV</div>

Upvotes: 1

Related Questions