Search code examples
c#jquerypostasp.net-mvc-5razorengine

Form is getting posted on any click event within the HTML.BeginForm MVC5


Form is getting posted(submited with blank model values) on any click event within the Html BeginForm. Due to which page is taking longer time to respond for other requests.I am using MVC5, jQuery-3.4.1.

Sample Controller Code:

Get Request :

public ActionResult Index()
 {
    // Some Logic to load Initial record for user
 }

Post Request :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ModalClass obj)
{
   // Logic to load Initial record based on filter on submit click
}

Sample View Code :

 @using (Html.BeginForm("Index", "ControllerName", FormMethod.POST, new { @id = "formid" }))
  {
    @Html.AntiForgeryToken()
    // Form Design Using Razor Syntax 
     <div class="form-group col-md-6 col-xs-12">
          <button type="submit" value="submit" class="btn btn-primary">Submit</button>
     </div>
  }

Output Image :

Image1: Page Design(Masked Few Field for security Reason):

enter image description here

Locations marked in yellow color if we click anywhere it POST the page with null model Values. If we click below thin green line which not included in the Html.BeginFrom no event is been called.

Image2: Network Call From Developer tool of Chrome:

enter image description here

Post request is called on click of dropdown as well as outside any control click. The screen shot attached is for localhost but we are facing the same issue on production also.

Kindly help me know the reason behind the same as, I am new to MVC also suggest some way to avoid this as my page response is getting delayed. Thank you in advance.

Rendered Page Source :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- Meta, title, CSS, favicons, etc. -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link href="/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="/Content/bootstrap-extended.css" rel="stylesheet" />
    <link href="/Content/font-awesome.min.css" rel="stylesheet" />
    <link href="/Content/nprogress.css" rel="stylesheet" />
    <link href="/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
    <link href="/Content/bootstrap-multiselect.css" rel="stylesheet" />
    <link href="/Content/Gridmvc.css" rel="stylesheet" />
    <link href="/Content/custom.css" rel="stylesheet" />

    <script src="/Scripts/jquery-3.4.1.min.js"></script>
    <script src="/Scripts/gridmvc.js"></script>


    <script type="text/javascript">
        $(document).ready(function () {
            $('.grid-table').addClass('table-bordered');
            window.history.pushState(null, "", window.location.href);
            window.onpopstate = function () {
                window.history.pushState(null, "", window.location.href);
            };
        });
    </script>
</head>
<body class="nav-md">
    <div class="container body full-height">
        <div class="main_container full-height">
            <div class="right_col" role="main">
                <script src="/Scripts/modernizr-2.6.2.js"></script>
                <script src="/Scripts/bootstrap.js"></script>
                <script src="/Scripts/bootstrap-multiselect.js"></script>
                <script src="/Scripts/bootstrap-session-timeout.js"></script>
                <script src="/Scripts/respond.js"></script>
                <script src="/Scripts/moment.min.js"></script>
                <script src="/Scripts/bootstrap-datetimepicker.min.js"></script>

                <script src="/Scripts/customNew.js"></script>

                <div class="page-title">
                </div>
                <div class="clearfix"></div>
                <div class="row">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <div class="panel panel-default">
                            <div class="panel-heading" style="padding:5px 15px">
                                <div class="panel-title">
                                    <h5 style="margin:5px 0">Title <a class="collapse-link"><i class="fa fa-chevron-up fa-fw"></i></a></h5>
                                </div>
                            </div>

                            <form action="/ControllerName" id="formid" method="post">
                                <input name="__RequestVerificationToken" type="hidden" value="Ek-WGhdZJz0xTglW6W6LbrCZn2c5wHqXm3VdIAReP71DvhRi7zhD-t9aMCzabOXs4CU8VjEQ9a0vT4I6GbeEuXI9ZAkoWmkgnxNZthcfPFzrKU4CsI5BeQN" />
                                <div class="panel-body">
                                    <div class="form-horizontal">
                                        <div class="form-group col-md-6 col-xs-12">
                                            <label class="control-label col-md-4 col-xs-6" for="LocationID" style="text-align:left">Locations</label>
                                            <div class="col-md-8 col-xs-6">
                                                <select class="form-control" data-val="true" data-val-number="The field Locations must be a number." data-val-required="The Locations field is required." id="ddlLocation" name="LocationID">
                                                    <option value="0">Value1</option>
                                                    <option value="1">Value2</option>
                                                </select>

                                            </div>
                                        </div>

                                        <div class="form-group col-md-6 col-xs-12">
                                            <label class="control-label col-md-4 col-xs-6" for="ClusterName" style="text-align:left">Cluster</label>
                                            <div class="col-md-8 col-xs-6">
                                                <select class="form-control" id="ClusterName" name="ClusterName">
                                                    <option value="0">Select</option>
                                                    <option value="1">Value1</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group col-md-6 col-xs-12">
                                            <label class="control-label col-md-4 col-xs-6" for="CustomerName" style="text-align:left">Customer Name</label>
                                            <div class="col-md-8 col-xs-6">
                                                <select class="form-control" id="CustomerName" name="CustomerName"></select>


                                            </div>
                                        </div>

                                        <div class="form-group col-md-6 col-xs-12">
                                            <label class="control-label col-md-4 col-xs-6" for="ProjectName" style="text-align:left">Project Name</label>
                                            <div class="col-md-8 col-xs-6">
                                                <select class="form-control" id="ProjectName" name="ProjectName"></select>
                                            </div>
                                        </div>

                                        <div class="form-group col-md-6 col-xs-12">
                                            <label class="control-label col-md-4 col-xs-6" for="Date" style="text-align:left">Date</label>
                                            <div class="col-md-8 col-xs-6">
                                                <div class="input-group datefield" style="margin-bottom:0px">
                                                    <input class="form-control text-box single-line" data-val="true" data-val-date="The field Date must be a date." data-val-required="Please select date" id="txtDate" name="Date" placeholder="Compliance Date" type="datetime" value="" />
                                                    <div class="input-group-addon">
                                                        <span class="glyphicon glyphicon-calendar" id="dateSearch" style="cursor:pointer"></span>
                                                    </div>
                                                    <span class="field-validation-valid" data-valmsg-for="Date" data-valmsg-replace="true"></span>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-group col-md-6 col-xs-12">
                                            <label class="control-label col-md-4 col-xs-6" for="ParamID" style="text-align:left"> Parameters</label>
                                            <div class="col-md-8 col-xs-6" style="height:34px !important">
                                                <select class="listbox form-control col-md-12" id="ParamID" multiple="multiple" name="ParamID">
                                                    <option value="1">Value1</option>
                                                    <option value="2">Value2</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group col-md-6 col-xs-12">
                                            <button type="submit" value="submit" class="btn btn-primary">Submit</button>
                                            <a class="btn btn-primary float-right" role="button" href="/Controller/DownloadExcel">Download Excel</a>
                                        </div>
                                        <div class="clearfix"></div>
                                    </div>

                                    <hr />

                                    <div class="form-group col-md-12 col-xs-12">
                                        <div class="col-md-5 col-xs-12 col-md-offset-3">
                                            <div class='progress progress_sm'>
                                                <div class='progress-bar bg-green' role='progressbar' style='width:100%;'>
                                                    Value2
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="table-responsive Linked">
                                        <div class="grid-mvc" data-lang="en" data-gridname="" data-selectable="true" data-multiplefilters="false">
                                            <div class="grid-wrap">
                                                <table class="table table-striped grid-table">

                                                    <thead>
                                                        <tr>
                                                            <th class="grid-header" style="width:30px;"><div class="grid-header-title"><span></span></div></th>
                                                            <th class="grid-header" style="width:30px;"><div class="grid-header-title"><span> </span></div></th>
                                                            <th class="grid-header" style="width:30px;"><div class="grid-header-title"><span>Delete</span></div></th>
                                                            <th class="grid-header"><div class="grid-filter" data-filterdata="[]" data-name="Name" data-type="System.String" data-widgetdata="null"><span class="grid-filter-btn" title="Filter this column"></span></div><div class="grid-header-title"><a href="?grid-column=Name&amp;grid-dir=0">Name</a></div></th>
                                                        </tr>

                                                    </thead>
                                                    <tbody>
                                                        <tr class="grid-row ">
                                                            <td class="grid-cell" data-name=""><a class="btn btn-default btn-round" data-backdrop="static" data-modal="" href="/Controller/Action1?Name=Value" ><span class='glyphicon glyphicon-new-window'></span></a></td>
                                                            <td class="grid-cell" data-name=""><span title='Non-Compliance' class='status inactive'> </span></td>
                                                            <td class="grid-cell" data-name=""><a class="btn btn-danger btn-round" href="/Controller/Action2/Value" onclick="return confirm(&#39;Are you sure want to delete this?);"><span class='glyphicon glyphicon-remove'></span></a></td>
                                                            <td class="grid-cell" data-name="Name">ABCDE</td>

                                                        </tr>
                                                    </tbody>
                                                </table>
                                                <div class="grid-footer">
                                                    <div class="grid-pager">
                                                        <ul class="pagination">

                                                            <li class="active"><span>1</span></li>
                                                            <li><a href="?grid-page=2">2</a></li>
                                                            <li><a href="?grid-page=3">3</a></li>
                                                            <li><a href="?grid-page=4">...</a></li>
                                                            <li><a href="?grid-page=66">66</a></li>
                                                            <li><a href="?grid-page=2">»</a></li>
                                                        </ul>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>




                                        <style type="text/css">
                                            .table .table-striped .grid-table .dataTable .no-footer {
                                                width: 100% !important;
                                            }

                                            .progress.progress_sm {
                                                /*width: 33% !important;*/
                                                float: left;
                                                z-index: auto !important;
                                                display: block;
                                                margin: 0px !important;
                                                position: relative !important;
                                                /* top: 0; */
                                                /* left: 0; */
                                                /*height: 100%;
                                            width: 100%;*/
                                                background-color: #ededed;
                                                background-image: none;
                                                border-radius: 25px;
                                            }

                                            .progress-bar span {
                                                font-weight: bold;
                                            }

                                            .gridDangerCell {
                                                color: red;
                                            }
                                        </style>


                                        <!-- modal placeholder-->
                                        <div id='myModal' class='modal fade in' data-keyboard="false" data-backdrop="static">
                                            <div class="modal-dialog modal-lg">
                                                <div class="modal-content">
                                                    <div id='myModalContent' class="modal-"></div>
                                                </div>
                                            </div>
                                        </div>

                                        <script type="text/javascript">
                                            $(document).ready(function () {
                                                $(".Linked .grid-row a").click(function () {
                                                    $(this).closest('.table').find(".grid-row.grid-row-selected").removeClass("grid-row-selected");
                                                    $(this).closest('.grid-row').addClass("grid-row-selected");
                                                });
                                            });
                                        </script>
                                    </div>
                                </div>
                            </form>

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

                <span id="progress" class="progress" style="display: none;">
                </span>
                <style type="text/css">
                    .progress {
                        z-index: 9999 !important;
                        display: block;
                        margin: 0px !important;
                        position: absolute;
                        background: url(images/Preloader_3.gif) center no-repeat #80808036;
                        top: 0;
                        left: 0;
                        bottom: 0;
                        right: 0;
                        height: 100%;
                        width: 100%;
                    }
                </style>

                <script type="text/javascript">

                    $(document).ready(function () {
                        var ErrorMessage = '';
                        if (ErrorMessage != "") {
                            alert(ErrorMessage);
                        }
                        $('.se-pre-con').hide();
                        $("#formID").submit(function (e) {
                            if ($('#formID').valid()) {
                                $('.se-pre-con').show();
                            }
                            else {
                                e.preventDefault();
                            }
                        });

                        $('.listbox').multiselect({
                            includeSelectAllOption: true,

                        });

                        var IsPost = 'False';
                        if (IsPost == 'False') {
                            $('.listbox').multiselect('selectAll', false);
                            $('.listbox').multiselect('updateButtonText');
                        }

                        $('.datefield').datetimepicker({
                            format: 'YYYY-MM-DD',
                            ignoreReadonly: true,
                            allowInputToggle: true
                        });

                        function CallAjax(data) {
                            var obj = {};
                            obj.InputDate = data;
                            $.ajax({
                                type: "GET",
                                contentType: "application/json; charset=utf-8",
                                url: "Controller/Action",
                                data: obj,
                                dataType: "json",
                                beforeSend: function () {
                                    $(".se-pre-con").fadeIn(1000);
                                },
                                complete: function () {
                                    $(".se-pre-con").fadeOut(500);
                                },
                                success: function (result) {

                                },
                                error: function (error) {
                                    $(".se-pre-con").fadeOut(500);
                                    alert("Something wrong happend.");
                                }
                            });
                        }

                        $('#ddlLocation').on('change', function () {
                            CallAjax("ABCE");
                        });
                    });

                </script>

                <style type="text/css">
                    .d-inline {
                        display: inline !important;
                    }
                </style>
            </div>

            <footer>
                <div class="pull-right">

                </div>
                <div class="clearfix"></div>
            </footer>
        </div>
    </div>
    <div class="se-pre-con"></div>
    <style>
        .se-pre-con {
            position: fixed;
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
            z-index: 9999;
            background: url('images/Preloader_3.gif')center no-repeat rgba(0, 0, 0, 0.03);
        }

        form.NoStyle:after {
            content: none !important;
        }
    </style>
    <script>
        $(window).on("load", function () {
            $('.userName').each(function () {
                var text = $(this).text();
                var escapeChar = escapeRegExp(text);
                text = escapeChar.replace("UserName\\", "");
                $(this).text(text);
            })
        });

        function escapeRegExp(string) {
            return string.replace(/[.*+?^${}()|[\]\\]/g, "\$&");
        }
    </script>
    <script type="text/javascript">
        $.sessionTimeout({
            keepAliveUrl: '#',
            logoutUrl: "Controller/ActionLogout",
            redirUrl: "Account/ActionLogout",
            warnAfter: 90,
            redirAfter: 120,
            countdownMessage: 'Redirecting in {timer} seconds.'
        });

        //Auto Hide Notification after 5 Sec.
        window.setTimeout(function () {
            $(".alert").fadeTo(0, 0).slideUp(1500, function () {
                $(this).remove();
            });
        }, 4000);

    </script>

    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="/Scripts/jquery.validate.js"></script>
    <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="/Scripts/jquery.dataTables.min.js"></script>

</body>
</html>

Console output for events bind to the form:

jQuery._data( $("#formID").get(0), "events" ); 

{submit: Array(2), reset: Array(1), keyup: Array(1), focusout: Array(1), focusin: Array(1), …}
click: Array(2)
0:
data: undefined
guid: 56
handler: ƒ delegate( event )
guid: 56
arguments: null
caller: null
length: 1
name: "delegate"
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: jquery.validate.js:411

1:
data: undefined
guid: 58
handler: ƒ ( event )
guid: 58
arguments: null
caller: null
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: jquery.validate.js:46

submit: Array(2)
0:
data: null
guid: 27
handler: ƒ (e)
guid: 27
arguments: null
caller: null
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: Report:822

1:
data: undefined
guid: 59
handler: ƒ ( event )
guid: 59
arguments: null
caller: null
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: jquery.validate.js:64

customNew.js Code

function init_sidebar() {
    var setContentHeight = function () {
        $NAV_MENU = $('.nav_menu');
        $FOOTER = $('footer');
        $RIGHT_COL.css('min-height', $(window).height());
        var bodyHeight = $BODY.outerHeight(),
            footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
            leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
            contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;
        contentHeight -= $NAV_MENU.height() + footerHeight;
        $RIGHT_COL.css('min-height', contentHeight);
    };
    $SIDEBAR_MENU.find('a').on('click', function (ev) {
        var $li = $(this).parent();
        if ($li.is('.active')) {
            $li.removeClass('active active-sm');
            $('ul:first', $li).slideUp(function () {
                setContentHeight();
            });
        } else {
            // prevent closing menu if we are on child menu
            if (!$li.parent().is('.child_menu')) {
                $SIDEBAR_MENU.find('li').removeClass('active active-sm');
                $SIDEBAR_MENU.find('li ul').slideUp();
            } else {
                if ($BODY.is(".nav-sm")) {
                    $SIDEBAR_MENU.find("li").removeClass("active active-sm");
                    $SIDEBAR_MENU.find("li ul").slideUp();
                }
            }
            $li.addClass('active');
            $('ul:first', $li).slideDown(function () {
                setContentHeight();
            });
        }
    });

    $MENU_TOGGLE.on('click', function () {
        if ($BODY.hasClass('nav-md')) {
            $SIDEBAR_MENU.find('li.active ul').hide();
            $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
        } else {
            $SIDEBAR_MENU.find('li.active-sm ul').show();
            $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
        }

        $BODY.toggleClass('nav-md nav-sm');

        setContentHeight();
    });

    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page');

    $SIDEBAR_MENU.find('a').filter(function () {
        return this.href == CURRENT_URL;
    }).parent('li').addClass('current-page').parents('ul').slideDown(function () {
        setContentHeight();
    }).parent().addClass('active');

        setContentHeight();

    // fixed sidebar
    if ($.fn.mCustomScrollbar) {
        $('.menu_fixed').mCustomScrollbar({
            autoHideScrollbar: true,
            theme: 'minimal',
            mouseWheel: { preventDefault: true }
        });
    }
}
$(document).ready(function () {
init_sidebar();
});

Solution

  • After lot of debugging and code segregation, we found the block of code causing the form post on click of the form controls.

    Below is the line of code which is causing form to get posted to the same Controller/Action :

    <script type="text/javascript">
            $.sessionTimeout({
                keepAliveUrl: '#',   //   This is culprit
                logoutUrl: "Controller/ActionLogout",
                redirUrl: "Account/ActionLogout",
                warnAfter: 90,
                redirAfter: 120,
                countdownMessage: 'Redirecting in {timer} seconds.'
            });
    </script>
    

    We are using this to check users session expiry and to increase the expiry time if user is active. We have used bootstrap-session-timeout.js to do so. In this file every time ajax post request is called to keepAliveUrl to check for the active session and increase the session time-out. If we are passing the value # the page is posted to current controller/action method.

    There are three possible solutions for the problem:

    1. Change ajaxType: 'POST' to 'GET' explicitly as follows :

    $.sessionTimeout({
                keepAliveUrl: '#',
                ajaxType: 'GET',            // Soultion
                logoutUrl: "Controller/ActionLogout",
                redirUrl: "Account/ActionLogout",
                warnAfter: 90,
                redirAfter: 120,
                countdownMessage: 'Redirecting in {timer} seconds.'
            });
    

    2. Provide separate keepAliveUrl instead of '#' will prevent the post on same page.

    $.sessionTimeout({
                    keepAliveUrl: '/keepAlive',  // Soultion          
                    logoutUrl: "Controller/ActionLogout",
                    redirUrl: "Account/ActionLogout",
                    warnAfter: 90,
                    redirAfter: 120,
                    countdownMessage: 'Redirecting in {timer} seconds.'
                });
    

    3. Change the keepalive flag to false, this will prevent the post request on each click.

    $.sessionTimeout({
                        keepAliveUrl: '#',
                        keepAlive: false,     // Solution     
                        logoutUrl: "Controller/ActionLogout",
                        redirUrl: "Account/ActionLogout",
                        warnAfter: 90,
                        redirAfter: 120,
                        countdownMessage: 'Redirecting in {timer} seconds.'