Steven
Steven

Reputation: 18859

Returning data after submitting a form in a partial view in jQuery dialog

I have a page that displays a list of Folders. I have a link that will open a partial view in a jQuery dialog, so that I can add a new Folder.

Here's what's in my main Index view:

<script type="text/javascript">

    $(document).ready(function () {

        $('#dialog').dialog({
            width: 540, height: 280, autoOpen: false, draggable: false,
            resizable: false, modal: true,
            open: function (event, ui) {
                $(this).load("@Url.Action("Create")");                   
            },
            close: function (event, ui) {
                $(this).empty();
            }
        });

        $('ul#folders li.add').click(function () {
            $('#dialog').dialog('open');
        });

    });

</script>

<ul id="folders">
    <li class="add"><span></span></li>
</ul>

<div id="dialog"></div>

When I click on the "Add" button, I'm loading a partial view into the jQuery dialog. Here's my partial view:

@model FolderViewModel

<h1>Create new folder</h1>

<div id="folder-create">
    @using (Ajax.BeginForm("Create", "Folders", null)) {
        @Html.AntiForgeryToken()

        @Html.TextBoxFor(m => m.Name, new { placeholder = "Name" })

        <p>@Html.ValidationSummary()</p>

        <input type="submit" class="create" value="" />
    }
</div>

<script type="text/javascript">
    $(document).ready(function() {
        $.validator.unobtrusive.parse("#folder-create > form");
    });
</script>

Here's the method the form is posting to:

[HttpPost]
public ActionResult Create(FolderViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        try
        {
            // create folder
        }
        catch
        {
            return View(viewModel);
        }
    }

    return View(viewModel);
}

Everything works fine here - the validation works and I can submit my form.

The only problem is that once I successfully submit my form, I want to close the modal and pass the new folder's id back to the Index view so that I can show a "X created successfully" message.

I imagine I need to return JSON instead of a ViewResult, and capture that result somewhere, but I'm not exactly sure how.

Upvotes: 0

Views: 861

Answers (1)

Fals
Fals

Reputation: 6839

You can bind a function to do something when the ajax request finish:

function OnSuccess(data) {
      /*Close the popup and do stuff here*/
}

The AjaxOptions to your Ajax.BeginForm should look like this:

 new AjaxOptions 
 { 
   /*Other properties*/
    OnSuccess ="OnSuccess(data)" 
 })

In the controller return the Id and anything else and use it on the OnSuccess function.

[HttpPost]
public JsonResult Create(FolderViewModel viewModel)
{
    /*Do stuff to create the folder*/
    return Json(/*return the Id and something else*/);
}

Upvotes: 2

Related Questions