AndreiM
AndreiM

Reputation: 886

Trigger controller actions in MVC when jQueryUi dialog is opened or closed

My model looks like:

class Store
{
    ...
    virtual ICollection<StoreItem> items;
    ...
}

The View for the Store Shows Store properties and a table with items and StoreItem properties. I want that when an Item is clicked, and a jQuery UI dialog is displayed to edit the Item model. For this, I created Views actions for StoreItem, and embedded a partial frame in the Dialog.

Something like:

<div id="modaldlg" title="Edit item?">
    @using (Ajax.BeginForm(
    new AjaxOptions
    {
        HttpMethod = "get",
        InsertionMode = InsertionMode.Replace,
    }))
    {
        @Html.Action("Edit", "StoreItem")
    }
</div>

My problems:

  1. The StoreItem controller action is triggered when the parent page loads. I want it to trigger when the dialog is displayed, because it depends on the item that was clicked.
  2. When I close the jQuery Dialog, I want to trigger a post -> the StoreItem's controller action. How do I do this?

Upvotes: 0

Views: 543

Answers (1)

Ron Brogan
Ron Brogan

Reputation: 901

While I can't be more accurate about a solution because I'm not sure how the parent view is structured, I'm doing something similar in a project of mine. Here's how I did it:

$('.itemContainer').on('click', '#buttonId', function (event) {
        event.preventDefault();
        $("#PlaceholderDiv").dialog({
            autoOpen: true,
            width: 450,
            height: 450,
            resizable: false,
            title: 'Edit Item',
            modal: true,
            open: function () { //Use the open handler to load data into the dialog.
                $('#loadingAnimation').show();
                $(this).load('/Controller/Action/' + itemId, function(){$('#loadingAnimation').hide();});
            },
            close: function () {
                $.ajax({
                     type: "POST", 
                     url: $('#formId').attr('action'), 
                     data: $('#formId').serialize()})
                .done(setTimeout(function() {RefreshPartial()}, (delayInms)));
            },
            buttons: {
                Close: function () {
                    $(this).dialog("close");
                }
            }
        });
        return false;
    });

Upvotes: 1

Related Questions