gchq
gchq

Reputation: 1775

MVC 5 - raise Bootstrap Modal from Controller

Coming from WebForms getting my head around some MVC stuff is not quite intuitive and I am struggling to find a way to modal to pop-up from the controller (depending upon the postback result)..

The modal

<div id="PopupModal" class="modal fade in out">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button class="close" aria-hidden="true" type="button" data-dismiss="modal">×</button>
                    <h4 class="modal-title" id="ModalTitle"></h4>
                </div>
                <div class="modal-body" id="ModalBody">
                    <h5 id="ModalBodyText"></h5>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-default" type="button" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>

This is how I would have raised the event in WebForms

Private Sub ModalValidation(Message As String)
        Try
            Dim SB As New StringBuilder
            SB.Append("$(document).ready(function(){")
            SB.Append("$('#PopupModal').modal();")
            SB.Append("var vBody = document.getElementById('ModalBodyText');")
            SB.Append("vBody.innerHTML = '" & Message & "';")
            SB.Append("var vTitle = document.getElementById('ModalTitle');")
            SB.Append("vTitle.innerHTML = 'Validation';")
            SB.Append("vTitle.style.color = 'orange';")
            SB.Append("});")
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ValidationShowModal", SB.ToString, True)
        Catch ex As Exception
            Dim vError As New SendError
            vError.MailError(60, PageName, ex)
        End Try
    End Sub

How can I raise the same event from the controller?

Thanks

Edit = Big thank you to Vitor Salgado for pointing me in the right direction

Added this to the controller - Index

Function Index() As ActionResult
        Dim vPopup As New UploadFilesResult
        If Not Session("PopupMessage") Is Nothing Then
            vPopup.PopupMessage = Session("PopupMessage")
        Else
            vPopup.PopupMessage = "None"
        End If

        ViewData("UploadFilesResult") = vPopup
        Return View("BlueImpMinView")
    End Function

Added this to Controller - ActionResult (where the action completed normally)

Session("PopupMessage") = "The file was successfully uploaded!"
        Return Redirect("/blueimp/Index#Completed")

Added a hidden field to the view

 @code
    Dim vPopup As MVPTest.UploadFilesResult = CType(ViewData("UploadFilesResult"), MVPTest.UploadFilesResult)
    Dim vPopupMessage As String = vPopup.PopupMessage
    @Html.TextBox("MessageTB", vPopupMessage, New With {.type = "hidden"})
End Code

and the javascript for the modal

<script>

window.onload = function () {
    var vType = location.hash;
    var vMessage = document.getElementById('MessageTB').value;
    switch (vType) {
        case '#Completed':
            //run code for completed modal

            $(document).ready(function () {
                $('#PopupModal').modal();
                var vBody = document.getElementById('ModalBodyText');
                vBody.innerHTML = vMessage;
                var vTitle = document.getElementById('ModalTitle');
                vTitle.innerHTML = 'Success';
                vTitle.style.color = 'green';
            });
            break;
        case '#Error':
            //run code for error modal

            break;
        case '#Validation':
            //run code for validation modal
    }


}


</script>

Upvotes: 1

Views: 8377

Answers (2)

Vitor Hugo Salgado
Vitor Hugo Salgado

Reputation: 141

In controller code, you could append to your querystring some marker parameter or return a specific cookie, then, in your javascript code, you can identify one of these marker values and show your modal window.

Here some sample code..

The controller

public ActionResult Register()
{
    return View();
}

[HttpPost]
public ActionResult Register(RegisterModel model)
{
    return Redirect("/Home/Register#registered");
}

The view

@using (Html.BeginForm())
{
    <label>Login</label><br />
    @Html.TextBoxFor(x => x.Login)

    <br />

    <label>Name</label><br />
    @Html.TextBoxFor(x => x.Name)

    <br />

    <label>Email</label><br />
    @Html.TextBoxFor(x => x.Emai)

    <br />

    <input type="submit" value="Register" />
}

<script type="text/javascript">

    window.onload = function () {
        if (window.location.hash == '#registered') {
            alert('Your modal code here!');
        }
    };

</script>

The action Register(POST) is the server side code that will create some marker to your client side code. In the sample, a added a hash value to url. You could return a cookie value or better, add some value to hidden field and read the value from it. In the view, a have simple JS code that executes on page load. The JS search for the hash value and show the modal.

Upvotes: 4

Bob Mac
Bob Mac

Reputation: 359

There are several ways to do this that fit within the MVC way of doing things. Here's what I would do...

If you need the server to decide whether or not to show the modal, but you don't wish to refresh the page, then AJAX is probably what you want. Use can use jQuery's ajax calls to post data to a controller action, make a decision on the server, then send back a result that your js can use to either show the modal or not. This way, the page does not need to refresh yet you make a round trip to the server to decide what you need to do.

Upvotes: 0

Related Questions