sábado, 10 de diciembre de 2016

Get result from MVC controller method without parameters using jQuery when PageReady event occurs


Add call controller method without parameters: 

NOTE that url = '/<controller>/<method>'

<script type="text/javascript">

    $(document).ready(function () {

        $.ajax({
            type: "GET",
            url: '/Home/ValidateSession',
            data: param = "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc
        });

        function successFunc(data, status) {
            if (!data) {
            $("#Modal").modal();
            }
        }

        function errorFunc() {
            alert('Ha ocurrido un error. Si el problema persiste contacte al proveedor de servicios.');
        }

    });

</script>


Add method on Home controller. This method returns true o false.

[HttpGet]
public ActionResult ValidateSession()
{
    var result = Session["ValidUser"] != null;
    return Json(result, JsonRequestBehavior.AllowGet);
}


The result value is returned to data for jQuery function that evaluate if it is true or false. If it is false the function shows an access-control popup window.

No useful for the example, but complementary. You can create popup window with bootstrap:

<div class="modal fade" id="Modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="well">
                ...
            </div>
        </div>
    </div>
</div>