Brennan Morell
Brennan Morell

Reputation: 85

Button submitting form to "Get" ActionResult instead of "Post"

I just took over a MVC Web Application for an employee who is no longer with the company I work for. The application is in the early development stage and I noticed an unresolved error where a 'submit' button triggers the view's corresponding HttpGet ActionResult, instead of the HttpPost ActionResult.

He included a lot of jQuery scripts in the view, and I originally suspected one of them could be causing the issue, however none seem to apply directly to the button.

Controller (named HomeController.cs):

[HttpGet]
    public ActionResult Create(string distributorObject)
    {
        StockLiftObjectView stockLiftObjectView = new StockLiftObjectView();
        var userInfo = User.Identity.Name.GetActiveDirectoryInfo();
        stockLiftObjectView.txtFirstName = userInfo.FirstName;
        stockLiftObjectView.txtLastName = userInfo.LastName;
        stockLiftObjectView.txtEmail = userInfo.Email;

        if (stockLiftObjectView.RegionId == Guid.Empty)
        {
            stockLiftObjectView.RegionsList = new SelectList(_stockLiftService.GetRegions(), "Id", "RegionName");
        }

        return View(stockLiftObjectView);
    }

    [HttpPost] //Haven't done anything here yet. Ths is never reached
    public ActionResult Create(string command, StockLiftObjectView stockLiftObjectView)
    {
        return View(stockLiftObjectView);
    }

View (named Create.cshtml):

@using Html.BeginForm("Create", "Home", FormMethod.Post, new {id = createStockLift}))
{ 
    //left out some non-useful code here
    <div class="col-md-offset-2 col-md-10">
                <table>
                    <tr><td><input type="submit" value="Create" name="command" class="btn btn-default" /></td></tr>
                    <tr><td><input type="submit" value="Save" name="command" class="btn btn-default" /></td></tr>
                </table>
    </div>
}

Script in View that I thought could be problematic:

<script type="text/javascript">
 function getview() {

        //runs everytime page loads

        $.get("@Url.Action("ShowPartial", "StockLiftAttachmentWebGrid",  new     List<hpd.Lynx.Web.StockLift.StockLiftAttachmentUpload>()))", function (data) {
            $("#stockliftattachmentpartial").replaceWith(data);
            $('#createStockLift').submit();
            });

        };
        $("#stockliftattachmentpartial").show();
</script>

I'm sorry my question isn't that specific. I've just been baffled by this issue for the past couple of days and can't think of a good way to describe the problem in a google search. As I said before, I'm not that well versed with jQuery so think I could be misunderstanding something simple.

UPDATE:

Only other time the getview() function is referenced is here...

<input type="submit" value="Upload File" title="Upload" id="btnUpload" onclick="javascript: getview(); return false;" />

so I don't understand why it executes when the page loads (I never click the upload button). Again, my misunderstanding is coming from never using more than basic scripts.

Other scripts in the view (don't seem applicable but I'll show in case)

<script>
    $(function () {
        $('#search').click(function () {
            var distributorNumber = $("#textboxDistributorNumber").val();
            var href = this.href + '?distributorNumber=' + distributorNumber;
            @*var url = "@Url.Action("DistributorPartial", "Distributor")"*@
            $('#dialog').dialog({
                width: 1175,
                height: 500,
                title: 'Distributor Search',
                modal: true,
                open: function (event, ui) {
                    $(".ui-dialog-titlebar-close").hide();
                    $(this).load(href, function (result) {
                        $('.forms').submit(function () {

                            $.ajax({
                                url: this.action,
                                type: this.method,
                                data: $(this).serialize(),
                                success: function (json) {
                                    debugger;
                                    $('#distributorViewModel_DistributorName').val(json.DistributorName);

                                }
                            });
                            return false;
                        });
                    });
                }
            });
            return false;
        });
    });
</script>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create</title>

   <link rel="stylesheet" type="text/css" href="http://hco/css/Main.css" />
    

    <link href="/Content/site.css" rel="stylesheet"/>

    <link href="/Content/themes/base/jquery.ui.theme.css" rel="stylesheet"/>


    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

    <script src="/Scripts/jquery.ui.datepicker.min.js"
            type="text/javascript"></script>
    <script src="/Scripts/DatePickerReady.js"
            type="text/javascript"></script>

    <script src="/Scripts/modernizr-2.7.2.js"></script>



    


    


   
  
</head>
<body>
    <form id="form1" runat="server">
        <div align="center">
            <table border="0" width="800" bgcolor="black" cellpadding="0" cellspacing="0">
                <tr>
                    <td>
                        <table border="0" cellpadding="0" cellspacing="0" width="800px">
                            <tr bgcolor="black" height="60px">
                                                <%--ADD FILLER, SRM 2/13/2012--%>
                                <td align="left" class="appTitle" style="width:100%;">
                                    <!--the title was here-->
                                    
                                    
                                </td>
                                <td valign="top" align="right">
                                    <table border="0" cellpadding="0" cellspacing="0">
                                        <tr>
                                           
                                        </tr>
                                        <tr valign="middle">
                                            <td><input style="padding:0,0,0,0;margin:0,0,0,0;" height="20px" type="text" name="txtSearch" id="txtSearch" /></td>
                                            <td><image height="22px" width="22px" style="background-color:White;padding:0,0,0,0;margin:0,0,0,0;" src="http://hco/images/SearchButton.jpg" alt="search" onclick="window.location='/site-search.aspx?search=' + document.all.txtSearch.value.trim()" onmouseover="this.style.cursor='hand'" />&nbsp;</td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr height="24px">
                                <td colspan="2" class="hcoNav">
                                    <table border="0" cellpadding="2" cellspacing="0" height="24" width="100%">
                                        <tr>
                                           
                                            <td></td>
                                            <td nowrap="nowrap" align="right">
                                                <table border="0" cellpadding="0" cellspacing="0">
                                                    <tr>
 
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" bgcolor="white" height="100%" valign="top" style="margin:0,0,0,0;">
                                    <div style="padding:10px;">
                                        <div id="page">

                                            <div class="container body-content">
                                                


                                          





<form action="/Home/Create" id="createStockLift" method="post"><input name="__RequestVerificationToken" type="hidden" value="xz4YzzvUUXUP-g5KCkPRb6Ox3dZ668tjmH6fKIIwL52zSnVjX-DfV0XDNVWaKMplGPCbm664TdiJDWwoWUeO70ET9nwsPGwsRv0DVxOgDyYLMA3d3CzvEh2Vzj0ftr6O0" />    <style type="text/css">
        .style1 {
            height: 35px;
        }
    </style>
    <br />
    <div id="lblRequired" align="center">
        <label for="lblRequired">* Required for saving</label>
    </div>
    <div align="center">
        <div style="text-align: left; clear: none;">
            <table cellpadding="2" border="1" align="center">

                <tr>
                    <td>
                        <b>*CTM First Name:</b>
                    </td>
                    <td>
                        <input class="textboxFirstName" id="txtFirstName" name="txtFirstName" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="txtFirstName" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>*CTM Last Name</b>
                    </td>
                    <td>
                        <input class="textboxLastName" id="txtLastName" name="txtLastName" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="txtLastName" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>*CTM Email:</b>
                    </td>
                    <td>
                        <input class="textboxEmail" id="txtEmail" name="txtEmail" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="txtEmail" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>*Your Region:</b>
                    </td>
                    <td>
                        <select data-val="true" data-val-required="The RegionId field is required." id="RegionId" na               <span class="field-validation-valid" data-valmsg-for="RegionId" data-valmsg-replace="true"></span>

                    </td>
                </tr>
                <tr>
                    <td>
                        <b>*Distributor:</b>
                    </td>
                    <td>
                        <label class="control-label col-md-2" for="Distributor_Number_Search_Text:_">Distributor Number Search Text: </label>
                        <input id="textboxDistributorNumber" name="Distributor" type="text" value="" /> <br />
                        <label class="control-label col-md-2" for="Distributor_Customer_Name_Search_Text:_">Distributor Customer Name Search Text: </label>
                        <input id="textboxDistributorName" name="DistributorPrincipalApprovalId" type="text" value="" />


                        <div id="dialog" title="Basic dialog">Please wait</div>
                        <a href="/Distributor/DistributorPartial" id="search">Search</a>
                        
                        <div id="divDistributor">
                            <input class="text-box single-line" id="distributorViewModel_DistributorName" name="distributorViewModel.DistributorName" type="text" value="" />
                        </div>
                        <span class="field-validation-valid" data-valmsg-for="Distributor" data-valmsg-replace="true"></span>

                    </td>
                </tr>

                <tr>
                    <td>
                        <b>End User:</b>
                    </td>
                    <td></td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="AccountManufactures">Account Manufactures:</label></b>
                    </td>
                    <td>
                        <input class="textboxAccountManufactures" id="AccountManufactures" name="AccountManufactures" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="AccountManufactures" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="InventoryRemovedFrom">Inventory removed from:</label></b>
                    </td>
                    <td>
                        <input class="textboxInventoyRemovedFrom" id="InventoryRemovedFrom" name="InventoryRemovedFrom" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="InventoryRemovedFrom" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="AnnualPotentialValue">*Annual potential for HPD products:</label></b>
                    </td>
                    <td>
                        <input class="textboxAnnualPotentialValue" data-val="true" data-val-number="The field *Annual potential for HPD products: must be a number." id="AnnualPotentialValue" name="AnnualPotentialValue" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="InventoryRemovedFrom" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="InventoryValue">*Competitive Inventory Value:</label></b>
                    </td>
                    <td>
                        <input class="text-box single-line" data-val="true" data-val-number="The field *Competitive Inventory Value: must be a number." id="InventoryValue" name="InventoryValue" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="InventoryValue" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="FiftyPercentMultiplier">*50% (.50) Multiplier:</label></b>
                    </td>
                    <td>
                        <input class="text-box single-line" data-val="true" data-val-number="The field *50% (.50) Multiplier: must be a number." id="FiftyPercentMultiplier" name="FiftyPercentMultiplier" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="FiftyPercentMultiplier" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="CreditDueValue">*CREDIT DUE DISTRIBUTOR:</label></b>
                    </td>
                    <td>
                        <input class="text-box single-line" data-val="true" data-val-number="The field *CREDIT DUE DISTRIBUTOR: must be a number." id="CreditDueValue" name="CreditDueValue" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="CreditDueValue" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="InitialOrderValue">*Value of the initial order:</label></b>
                    </td>
                    <td>
                        <input class="text-box single-line" data-val="true" data-val-number="The field *Value of the initial order: must be a number." id="InitialOrderValue" name="InitialOrderValue" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="InitialOrderValue" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="StockLiftMaterialScrappedDate">Stocklift material was scrapped(Date):</label></b>
                    </td>
                    <td>
                        <input class="text-box single-line" data-val="true" data-val-date="The field Stocklift material was scrapped(Date): must be a date." id="StockLiftMaterialScrappedDate" name="StockLiftMaterialScrappedDate" type="datetime" value="" />
                        <span class="field-validation-valid" data-valmsg-for="StockLiftMaterialScrappedDate" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="DistributorPrincipalApprovalId">Distributor Principal (Signature):</label></b>
                    </td>
                    <td>
                        <input class="text-box single-line" id="DistributorPrincipalApprovalId" name="DistributorPrincipalApprovalId" type="text" value="" />
                        <span class="field-validation-valid" data-valmsg-for="DistributorPrincipalApprovalId" data-valmsg-replace="true"></span>

                        <b><label class="control-label col-md-2" for="DistributorPrincipalApprovalDate">Date:</label></b>
                        <input class="text-box single-line" data-val="true" data-val-date="The field Date: must be a date." id="DistributorPrincipalApprovalDate" name="DistributorPrincipalApprovalDate" type="datetime" value="" />
                        <span class="field-validation-valid" data-valmsg-for="DistributorPrincipalApprovalDate" data-valmsg-replace="true"></span>

                        <div id="distributorDiv">
                        </div>

                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="Comments">Comments:</label></b>
                    </td>
                    <td>
                        <textarea class="textboxComments" cols="55" id="Comments" name="Comments" rows="10">
</textarea>
                        <span class="field-validation-valid" data-valmsg-for="Comments" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="AdministrativeNotes">Administrative Notes:</label></b>
                    </td>
                    <td>
                        <textarea class="textboxAdministrativeNotes" cols="55" id="AdministrativeNotes" name="AdministrativeNotes" rows="10">
</textarea>
                        <span class="field-validation-valid" data-valmsg-for="AdministrativeNotes" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="RejectedReason">Rejected Reason:</label></b>
                    </td>
                    <td>
                        <textarea class="textboxRejectedReason" cols="55" id="RejectedReason" name="RejectedReason" rows="10">
</textarea>
                        <span class="field-validation-valid" data-valmsg-for="RejectedReason" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                
                <tr>
                    <td>
                        <b><label class="control-label col-md-2" for="FileName">Stocklift Attachment:</label></b>
                    </td>
                    <td>
                        <input type="file" name="files" value="" multiple="multiple" />
                        <input type="submit" value="Upload File" title="Upload" id="btnUpload" onclick="javascript: getview(); return false;" />

                        <div style="color:Red;font-size:14px"></div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <div id="stockliftattachmentpartial">
        
    </div>
            <div class="col-md-offset-2 col-md-10">
                <table>
                    <tr><td><input type="submit" value="Create" name="command" class="btn btn-default" /></td></tr>
                    
                    
                    <tr><td><input type="submit" value="Save" name="command" class="btn btn-default" /></td></tr>
                </table>
            </div>
</form><table>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td align="left"><a href="/">Back to List</a></td>
    </tr>

</table>





                                            </div>

                                        </div>

                                    </div>
                                </td>
                        </table>
                    </td>
                </tr>
            </table>
        </div>
    </form>

    
    
    <script type="text/javascript">

     



        function getview() {

            $.get("/StockLiftAttachmentWebGrid/ShowPartial?Capacity=0&amp;Count=0)", function (data) {
                $("#stockliftattachmentpartial").replaceWith(data);
                $('#createStockLift').submit();
            });

        };
        $("#stockliftattachmentpartial").show();


        


        //{

        //    $.get("<~/Controllers/StockLiftAttachmentWebGridController/ShowPartial()>", function (data) { $("#stockliftattachmentpartial").html(data); }
        //)
        //}


        //$('#stockliftattachmentpartial').load('/Views/StockLiftAttachmentWebGrid/StockLiftAttachmentWebGrid');



    </script>

    <script>
        // var $loading = $('#divDistributor').hide();

        $(function () {
            $('#search').click(function () {
                var distributorNumber = $("#textboxDistributorNumber").val();
                var href = this.href + '?distributorNumber=' + distributorNumber;
                
                $('#dialog').dialog({
                    width: 1175,
                    height: 500,
                    title: 'Distributor Search',
                    modal: true,
                    open: function (event, ui) {
                        $(".ui-dialog-titlebar-close").hide();
                        $(this).load(href, function (result) {
                            $('.forms').submit(function () {

                                $.ajax({
                                    url: this.action,
                                    type: this.method,
                                    data: $(this).serialize(),
                                    success: function (json) {
                                        //$('#dialog').dialog('close');
                                        // $loading.show();
                                        debugger;
                                        $('#distributorViewModel_DistributorName').val(json.DistributorName);

                                    }
                                });
                                return false;
                            });
                        });
                    }
                });
                return false;
            });
        });
</script>

Upvotes: 2

Views: 650

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

Update:

Having now seen the full output page HTML, you have nested <form> elements which is invalid and probably causing the problems.

You need to place the forms so that they are not nested in the DOM hierarchy.

First thoughts:

Just a theory: But if I understand the picture from the initial clues, your problem may occur when you do a "search" first. This opens a dialog, populates it with a form, then quite stupidly attaches a permanent submit event handler to every form that exists on the page at the time with class="forms".

The following will fix that one piece of silliness:

      open: function (event, ui) {
         var $panel = $(this);
         $(".ui-dialog-titlebar-close").hide();
         $panel.load(href, function (result) {
              $('.forms', $panel).submit(function () {

The fix is to add a scope to the submit handler, e.g. with $('.forms', $panel), so it does not steal all submits from all .forms on the page! It will target only .forms in the panel loaded.

Advice: Look for any other jQuery code, anywhere, that uses submit( and regard it as a potential problem.

Upvotes: 2

Related Questions