locked
Submit function broken after revision RRS feed

  • Question

  • User-1641868886 posted

    I have a "Submit" function for a popup form for an "Add New" feature of a datatable. It has been working fine, until I recently made a revision, adding two elements. Here from my backup files is the "submit" function from the previous version:

    function SubmitForm(form) {
                $.validator.unobtrusive.parse(form);
                          
                var Vend_Id = $("#Vend_Id :selected").val()
                if ($(form).valid()) {
                     
                    $.ajax({
                        type: "POST",
                        url: form.action,
                        data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice"].indexOf(r.name) < 0
                        }),
                        success: function (data) {
                            
                            if (data.success) {
                                Popup.dialog('close');
                                dataTable.ajax.reload();
                                $.notify(data.message, {
                                    globalPosition: "top center",
                                    className: "success"
                                })
    
                            }
                        }
    
                    });
                }
                return false;
            }

    (One note:  It may not matter for this question, but the reason for filtering the array is "Vend_Id", to filter out parameters from the first two of three-part cascading ddl to arrive at "Vend_Id" localized by state, city.)

    Now, here is the revision. It adds the parameter "Whol_Id". Also added, inside of this popup, is a second popup for creating a new "sku" if the user's choice does not exist in the "sku" search.:

    function SubmitPopupForm_Add_Edit(form) {
    
                $.validator.unobtrusive.parse(form);
                debugger;           
                var Vend_Id = $("#Vend_Id :selected").val();
                var Whol_Id = $("#Whol_Id :selected").val();
                if ($(form).valid()) {
                    
                    $.ajax({
                        type: "POST",
                        url: form.action,
                        data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice", "Whol_Id"].indexOf(r.name) < 0
                        }),
                        success: function (data) {
                            
                            if (data.success) {
                                Popup.dialog('close');
                                dataTable.ajax.reload();
                                $.notify(data.message, {
                                    globalPosition: "top center",
                                    className: "success"
                                })
    
                            }
                        }
    
                    });
                }
                return false;
            }

    In stepping through the client debugger, I see the array is filled with the inputs I type/choose in filling the form. BUT when I proceed to the "AddOrEdit" controller, I correctly see "Groc_Id = 0" and "user = [logged-in user]". But as soon as I step to the first form item, "sku" the controller shows "null." Also, the dynamic of the view on my VS shows an error "return outside function." AGAIN, this function operated perfectly in the previous/backup version, and still does (never any error about "return outside function").

    FACTOR possibly creating the error:  The "AddOrEdit" popup form has an "@html.EditorFor: sku" but now the inner popup "CreateSku" also has an "@html.EditorFor: sku" to create the new "sku". Is it possible the controller is confused which "@html.EditorFor: sku" to read from? You can see that I changed the function name of the submit (also the Popup form names, AND the submit btn tags to match) and as mentioned above, the function on debugging shows the correct inputs from the form--to be sent to the controller. But in this revised version, the controller is obviously NOT receiving the form data.

    Am I missing something really simple here (I have checked and re-checked brackets, etc.)? Any suggestions appreciated. Also let me know if razor view info and/or controller method needed to see/analyze.

    Thanks much. 

     

    Tuesday, March 3, 2020 4:15 PM

Answers

  • User-1641868886 posted

    Update:  I solved this problem, the form now posts to the controller. But I have a question. I ADDED one element to my serialized (filtered) array, and it stopped working. Here is the change I made that fixed it:

    data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice"].indexOf(r.name) < 0
                        }),
    
    ...changed to:
    
    data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice", "Whol_Id"].indexOf(r.value) < 0
                        }),

    The added element, "Whol_Id" is highlighted in green, and the change from "r.name" to "r.value" is in yellow. Before I altered this function to add the element "Whol_Id" which is from a ddl, "r.name" worked fine, but not after the change. I'm reading a little bit to try to learn the reason (I'm no expert on javascript by any means) but if anybody knows, plz comment.

    Thanks much,

    RC

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 6, 2020 2:34 PM

All replies

  • User-1330468790 posted

    Hi, ReidMelSam,

    I also checked the code and it turns out that the code you provided seems correct. There is no bracket missing which will bring the error "return outside function" and you don't put the function in action property of the form. 

    Could you please show me the related html/.aspx markup? For example, the pop forms that you used to submit ID or other information including where you put "@html.EditorFor: sku" in the forms . Since you made the modification on the markup, there might be unexpected error inside the markup.

    What's more, why do you think the controller is confused from the @tag? Is there anything that the controller will to with the post data? If so, provide the relate code or illustrate what the controller process the data.

    I think it might help me to reproduce the error.

    Best regards,

    Sean

    Wednesday, March 4, 2020 7:13 AM
  • User-1641868886 posted

    Thanks much to you and anyone else who is looking at this.

    Here are some cshtml view elements. To be brief, I'm not including many of the tags that have NOT been altered with the revision. First, the tag in "Index.cshtml" that calls the "AddOrEdit" popup:

    <a id="AddEditLink" class="btn btn-success" style="margin:10px" onclick="PopupForm_Add_Edit('@Url.Action("AddOrEdit", "GrocBills")')"><i class="fa fa-plus"></i> Add New</a>

    ...now here, within the "AddOrEdit.cshtml" are the tags changed/added to 1) submit the "AddOrEdit" form, and 2) call the "CreateSku" popup from WITHIN the "AddOrEdit.cshtml" popup:

    (submit tag...)
    
    @using (Html.BeginForm("AddOrEdit", "GrocBills", FormMethod.Post, new { onsubmit = "return SubmitPopupForm_Add_Edit(this)" }))
    
    ...
    
    (new tag to call "CreateSku" popup...)
    
    <div id="addSkuDiv">
                    <span style="padding-right:55px" class="lead">Click to Create sku:</span>  <a id="SkuAddLink" class="btn btn-warning" onclick="PopupForm_2('@Url.Action("CreateSku", "GrocBills")')"><i class="fa fa-plus"></i> Create SKU</a>
                </div>
    
    (revised tag to submit the "AddOrEdit" form...)
    
    <input id="AddEditSend" type="submit" value="Submit" onclick="SubmitPopupForm_Add_Edit" class="btn btn-primary" style="margin-right:40px" />
    

    ...there are actually two (2) popup dialogs called from within the "AddOrEdit" popup form. First is the "Createsku" and second is "AddOrEdit" for "Vend_Id". They also have specific function names and submit function names, to try to alleviate confusion in the javascript.

    Finally, here is the controller action for "AddOrEdit" that is NOT receiving the form data after the revisions:

           [HttpPost]
            public ActionResult AddOrEdit(GrocBillsModel gro)
            {
    
                DynamicParameters param = new DynamicParameters();
    
                var userName = User.Identity.GetUserName();
                param.Add("@Groc_Id", gro.Groc_Id);
                param.Add("@userName", userName);
                param.Add("@sku", gro.sku);
                param.Add("@Vend_Id", gro.Vend_Id);
                param.Add("@Cashier", gro.Cashier);
                param.Add("@DateOfSale", gro.DateOfSale);
                param.Add("@Price", gro.Price);
                param.Add("@NetPrice", gro.NetPrice);
                param.Add("@Whol_Id", gro.Whol_Id);
                DataAccess.ExecuteWithoutReturn("spGrocBills_AddorEdit", param);
                
                return Json(new { success = true, message = "Saved/Updated Successfully" }, JsonRequestBehavior.AllowGet);
                
            }

    To repeat from my initial post, when I am stepping through the debug for the controller, I can see the inputs for "Groc_Id" and for "userName" but when I hit the first form element "sku" I get "null". So for some reason, the revisions I have done have disconnected the javascript from sending the form data to this controller.

    Thanks again to all for looking and any suggestions.

    Rc

     

    Wednesday, March 4, 2020 3:04 PM
  • User-1641868886 posted

    Update:  I solved this problem, the form now posts to the controller. But I have a question. I ADDED one element to my serialized (filtered) array, and it stopped working. Here is the change I made that fixed it:

    data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice"].indexOf(r.name) < 0
                        }),
    
    ...changed to:
    
    data: $(form).serializeArray().filter(function (r) {
                            return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice", "Whol_Id"].indexOf(r.value) < 0
                        }),

    The added element, "Whol_Id" is highlighted in green, and the change from "r.name" to "r.value" is in yellow. Before I altered this function to add the element "Whol_Id" which is from a ddl, "r.name" worked fine, but not after the change. I'm reading a little bit to try to learn the reason (I'm no expert on javascript by any means) but if anybody knows, plz comment.

    Thanks much,

    RC

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 6, 2020 2:34 PM
  • User-1330468790 posted

    Hi, ReidMelSam,

     

    Glad that you solved your previous problem.

    Now your problem seems that is related to javascript stuff.

    Though it is confusing as it filters the key-value pairs which does not contain the key in the array so that the controller would not receive the data of the filtered key.

     

    For example, I was given a form like below:

    Script and Razor page:

    <script type="text/javascript">
        
        function SubmitPopupForm_Add_Edit(form) {
    
            $.validator.unobtrusive.parse(form);
    
            var Vend_Id = $("#Vend_Id :selected").val();
            
            var Whol_Id = $("#Whol_Id :selected").val();
            
    
            if ($(form).valid()) {
    
                $.ajax({
                    type: "POST",
                    url: form.action,
                    data: $(form).serializeArray().filter(function (r) {
                        return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice", "Whol_Id"].indexOf(r.name) < 0
                    }),
                    success: function (data) {
    
                        if (data.success) {
                            console.log(data);
                        }
                    }
    
                });
            }
    
            return false;
        }
    </script>
    @model GrocBillsModel
    ......

    @using (Html.BeginForm("AddOrEdit", "GrocBills", FormMethod.Post, new { id = "form1", onsubmit = "return SubmitPopupForm_Add_Edit(this)" })) { <div> @Html.TextBoxFor(m => m.Groc_Id, new { id = "text1" }) </div> <div> @Html.TextBoxFor(m => m.sku, new { id = "text2" }) </div> <div> @Html.TextBoxFor(m => m.userName, new { id = "text3" }) </div> <div> @Html.TextBoxFor(m => m.Cashier, new { id = "text4" }) </div> <div> @Html.TextBoxFor(m => m.DateOfSale,"{0:yyyy-MM-dd}", new { id = "text5" }) </div> <div> @Html.TextBoxFor(m => m.Price, new { id = "text6"}) </div> <div> @Html.TextBoxFor(m => m.NetPrice, new { id = "text7" }) </div> <div> <select id="Whol_Id" name="Whol_Id"> <option value="5" selected="selected">5</option> <option value="6">6</option> <option value="7">7</option> </select> </div> <div> <select id="Vend_Id" name="Vend_Id"> <option value="1" selected="selected">1</option> <option value="2">6</option> <option value="3">7</option> </select> </div> <input id="AddEditSend" type="submit" value="Submit" onclick="SubmitPopupForm_Add_Edit" class="btn btn-primary" style="margin-right:40px" /> }

    The populated model value:

    public ActionResult View1()
            {
                GrocBillsModel groc = new GrocBillsModel() { 
                    Groc_Id = 1, userName = "name1", sku = "some sku", Cashier = "Cashier1", DateOfSale = new DateTime(2020, 3, 4), Price = 999, NetPrice = 888 };
    
                return View("View1", groc);
            }

     

    Then I clicked the submit.

    The serialized array 

    $(form).serializeArray()

    will be

    [
       {
          "name":"Groc_Id",
          "value":"1"
       },
       {
          "name":"sku",
          "value":"some sku"
       },
       {
          "name":"userName",
          "value":"name1"
       },
       {
          "name":"Cashier",
          "value":"Cashier1"
       },
       {
          "name":"DateOfSale",
          "value":"2020-03-04"
       },
       {
          "name":"Price",
          "value":"999"
       },
       {
          "name":"NetPrice",
          "value":"888"
       },
       {
          "name":"Whol_Id",
          "value":"5"
       },
       {
          "name":"Vend_Id",
          "value":"1"
       }
    ]
    

    After filtered,

    $(form).serializeArray().filter(function (r) {
    return ["UserName", "sku", "Vend_Id", "Cashier", "DateOfSale", "Price", "NetPrice", "Whol_Id"].indexOf(r.name) < 0
    });

    it will be 

    [
       {
          "name":"Groc_Id",
          "value":"1"
       },
       {
          "name":"userName",
          "value":"name1"
       }
    ]

    To summarise:

    1.You should not use "r.value" to replace "r.name" since the latter one represents the values which are the keys listed in the given array and also are the properties of the model.

    2.If you add "Whol_Id" to the given array, the value of the "Whol_Id" property will be filtered and not passed to the controller.

     

    Hope this could be helpful for you to figure out the reason why it stopped working.

     

    Best regards,

    Sean

    Tuesday, March 10, 2020 6:14 AM