nightmare637
nightmare637

Reputation: 635

How can I get my Popup to close on submit button from AJAX call in ASP.NET MVC?

I have a view that lists a bunch of items. I'm trying to make it so that when a user clicks on the "Action Event" for one of these items (from a table row), a pop-up will appear. The user can then update same information about this item, and either submit the information or close it. Regardless of which option they choose, I'm trying to get the pop-up window to close.

I'm 90% there, I just can't seem to work out one little detail - closing the popup after the submit button is pressed! A lot of the solutions I have seen don't appear to be working, and I just seem to be having some trouble tweaking them to work with my issue. Given the following code, what changes do I need to do to make this work?

Here is what I have:

View

Index.cshtml

<table>
@foreach (var item in Model)
    <tr>
        <td colspan="5" align="right">
                <a href="javascript:void(0);" class="anchorDetail" data-id="@item.AID">Action Event</a>
            </td>
        </tr>
    }
</table>


<div id="myModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div id="myModalContent"></div>
        </div>
    </div>
</div>

<script>
    var TeamDetailPostBackURL = '/Database/Edit';
        $(function () {
                $(".anchorDetail").click(function () {
                        var $buttonClicked = $(this);
                        var id = $buttonClicked.attr('data-id');
                        var options = { "backdrop": "static", keyboard: true };
                        $.ajax({
                                type: "GET",
                                url: TeamDetailPostBackURL,
                                contentType: "application/json; charset=utf-8",
                                data: { "Id": id },
                                datatype: "json",
                                success: function (data) {
                                        $('#myModalContent').html(data);
                                        $('#myModal').modal(options);
                                        $('#myModal').modal('show');                   

                                },
                                error: function () {
                                        alert("Dynamic content load failed.");                    
                                }
                        });
                });
        });

</script>

Popup View

Edit.cshtml

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.AID)
        <table>
        <tr>
         <td>@Html.LabelFor(model => model.Comment)</td>
         <td>@Html.TextAreaFor(model => model.Comment, new { @class = "form-control", rows = "5" })</td>
        </tr>
        <tr>
         <td><input type="submit" value="Save" class="btn btn-primary" id="btnSave"/></td>
         <td><button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button></td>
        </tr>
    </table>
     </div>
}

Controller

DatabaseController.cs

    public ActionResult Index()
    {
        return View(db.ActionableEvents.ToList());
    }

    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ActionableEvents actionableEvents = db.ActionableEvents.Find(id);
        if (actionableEvents == null)
        {
            return HttpNotFound();
        }
        return View(actionableEvents);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "AID,Comment")] ActionableEvents actionableEvents)
    {
        if (ModelState.IsValid)
        {
            db.Entry(actionableEvents).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(actionableEvents);
    }

I did see this resource here: asp.net submit button close Jquery Ajax, but I'm just not seeing how I would be able to tweak this into what I've got going on right now.

The cancel button I have right now works perfectly. Is there some way to use data-dismiss for my submit button and have it still save the data like I have for the cancel button? I've also seen some solutions use an onClick() parameter in the submit button, but then it would use a window.close() option. I don't want the entire window to close, nor do I want the user to be prompted about it either.

What is a good way I can approach this problem? I want my submit button to work just like my cancel button, only save the data. Thanks in advance for any advice!!!

Upvotes: 2

Views: 6000

Answers (2)

nightmare637
nightmare637

Reputation: 635

So, after a lot of playing around, I was able to come up with the following solution:

View

Index.cshtml

<table>
@foreach (var item in Model)
    <tr>
            <td>
                <button class="btn btn-primary" onclick="ActionAway(@item.AID)">Action Event</button>
            </td>
    </tr>
    }
        </tbody>
</table>

<div class="modal fade" id="myModal1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <a href="#" class="close" data-dismiss="modal">&times;</a>
                <h3 class="modal-title">Action This Event</h3>
            </div>
            <div class="modal-body" id="myModalBodyDiv1">

            </div>
        </div>
    </div>
</div>
</div>

<script>
    var ActionAway = function (theid) {
        var url = "/Database/Edit?id=" + theid;

        $('#myModalBodyDiv1').load(url, function () {
            $('#myModal1').modal("show");
        })
    }

</script>

Pop-up View

Edit.cshtml

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.AID)
        <table>
        <tr>
         <td>@Html.LabelFor(model => model.Comment)</td>
         <td>@Html.TextAreaFor(model => model.Comment, new { @class = "form-control", rows = "5" })</td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Save" class="btn btn-primary" id="btnSave"/>
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
        </td>
        </tr>
    </table>
     </div>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

<script>
    $(document).ready(function () {
    $("#btnSave").click(function () {
        $.ajax({
            success: function () {
                $("#myModal").modal("hide");
            }
        })
    })
})
</script>

The controller I was able to leave as it was without making any changes. Thanks again for all the help!

Upvotes: 0

iamdlm
iamdlm

Reputation: 1973

Can you try the following in your Index.cshtml (make sure you set an id for the form and correct it below):

$("form").submit(function(){
   $('#modal').modal('toggle');
});

If you want to make an AJAX request to the server and save the data you can do as follows (just include the code below in a click event on the dismiss button from the modal):

$.ajax({
    type: "POST",
    url: "SaveData",
    content: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(data),
    success: function (result) {
        // do something
    },
    error: function (result) {
        // do something
    }
});

And have a MVC action similiar to:

[HttpPost]
public JsonResult SaveData()
{
    // save data
}

Edit: After a second reading of your question, you need to make Edit.cshtml a partial view, then on Index.cshtml include your partial view in the div for the modal like this:

<div id="myModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            @Html.Partial("_EditView")
        </div>
    </div>
</div>

And your JS should look like this:

$("form").submit(function () {
    e.preventDefault();

    formData = $(this).serialize();

    $.ajax({
        type: "POST",
        url: "SaveData",
        content: "application/json; charset=utf-8",
        dataType: "json",
        data: formData ,
        success: function (result) {
            // do something
        },
        error: function (result) {
            // do something
        }
    });

    $('#modal').modal('toggle');
});

The JS should be in the Index.cshtml because that's where your partial exists, try it and you'll see.

Upvotes: 3

Related Questions