locked
Prevent default submit action does not work in partial view to call method by Ajax RRS feed

  • Question

  • User991566988 posted

    Hi

    I'm Trying to call this method in ArticleImagesTrController to add a new record (after call of get method by ajax successfully) in the previous Edit view:

            [HttpPost]
            public IActionResult Add([FromBody]ArticleImagesTr obj)
            {
                _context.Add(obj);
                _context.SaveChanges();
                return new JsonResult(obj);
            }

    Now when I try to call the previous method by Ajax in ParArticleImages partial view like this:

    @model Articles
    
    @*Some code*@
    
        <div class="modal fade" id="AjaxMod" tabindex="-1" role="dialog" aria-labelledby="addContactLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content mod">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addContactLabel">Translation</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body">
    
                        <form id="save" name="form">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <div>
                                            <label>Language</label>
                                            <select class="form-control" id="la">
                                                <option value="0"> Arabic</option>
                                                <option value="1" selected> English</option>
                                            </select>
                                        </div>
                                        <input type="text" class="form-control" id="masid" name="mas-id" />
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group" dir="ltr">
                                        <label>Title</label>
                                        <input type="text" id="ti" class="form-control" />
                                        <label>Details</label>
                                        <textarea rows="9" class="form-control" id="de"></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal" name="cl">Close</button>
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </form>
    
                    </div>
                </div>
            </div>
        </div>
    <script>
        $(function () {
            $("#save").submit(function (e) {
                e.preventDefault();
                var options = {};
    
                options.url = "/ArticleImagesTr/Add";
                options.type = "POST";
    
                var obj = {};
                obj.langId = select;
    
                obj.articleImageId = $('#masid').val(); // I have it by Ajax get method successfully
                obj.imageTitle = $("#ti").val();
                obj.details = $("#de").val();
    
                options.data = JSON.stringify(obj);
                options.contentType = "application/json";
                options.dataType = "json";
                if (!obj.imageTitle || !obj.details) {
                    toastr.error('All fields required!', { timeOut: 5000 });
                }
                else {
                    options.success = function (msg) {
                        toastr.success('Saved!', { timeOut: 5000 });
                    };
                    $.ajax(options);
                    $('#AjaxMod').modal('hide');
                }
    
                options.error = function () {
                    toastr.error('Not done!', { timeOut: 5000 });
                };
    
            });
         });
    </script>

    Now when I press submit button it returned blank page as the submit of Edit view it self not calling the previous method by Ajax.

    Why? and how to solve please?

    Friday, August 28, 2020 4:21 PM

Answers

  • User585649674 posted

    Change from

    <button type="submit" class="btn btn-primary">Save</button>

    Change To

    <button type="button" class="btn btn-primary">Save</button>

    If you are using Jquery Ajax, "<form>" tag is not needed. "<form>" tag is needed only for UnObtrusive ajax or simple posting of the form

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 31, 2020 9:15 AM

All replies

  • User475983607 posted

    musbah7@hotmail.com

    Now when I press submit button it returned blank page as the submit of Edit view it self not calling the previous method by Ajax.

    The blank page points to a problem with the overall design but I can only guess.  JavaScript libraries are loaded at the end of the document.  Assuming you are using the the standard MVC layout template without modification, then the JavaScript/jQuery within the partial is loading before the jQuery library.   This causes an error.  The JavaScript within the partial is ignored and explains the blank page.  Clicking the button, causes a standard form post and the associated action returned an empty page.

    Use the browser's developer tools to debug your code.  Errors are clearly shown in the console.  The network trace allow you to see if there's a full post back.  Let us know what's going on with your code.  

    Friday, August 28, 2020 7:28 PM
  • User991566988 posted

    I'm using a template different from the standard MVC shared layout page, And everything about jQuery is working fine with me depending on this shared layout. Like calling Ajax for Get and Post in another thanslation modals successfully (but without calling a partial view like this case).

    I'm using Firefox and Console gives me 'Bad request', When I saw network it gives me a full Request for the calling Articles/Edit view returning the main record of Articles and its child records of ArticleImages. But in response there is "No response data available for this request" with the blank page returned of course.

    Sunday, August 30, 2020 8:57 AM
  • User475983607 posted

    I'm using a template different from the standard MVC shared layout page, And everything about jQuery is working fine with me depending on this shared layout. Like calling Ajax for Get and Post in another thanslation modals successfully (but without calling a partial view like this case).

    Standard practice places JavaScript libraries and code at the end of the main page.   Partial views should not have JavaScript since the JavaScript can show up any place in the page.  Should we assume you are not following standards?

    No response data available for this request" with the blank page returned of course.

    AJAX does not refresh the page.  The response is returned to the AJAX success handler.   If you see a blank page in the browser window then there are issues with the JavaScript design.  I assume what's actually happening is the code is doing a full post back.  I can't see all the code so I'm unable to reproduce the results.

    Sunday, August 30, 2020 1:11 PM
  • User585649674 posted

    Change from

    <button type="submit" class="btn btn-primary">Save</button>

    Change To

    <button type="button" class="btn btn-primary">Save</button>

    If you are using Jquery Ajax, "<form>" tag is not needed. "<form>" tag is needed only for UnObtrusive ajax or simple posting of the form

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 31, 2020 9:15 AM
  • User991566988 posted

    You are right.

    Thanks

    Friday, September 4, 2020 8:28 AM
  • User475983607 posted

    I doubt the suggested changes fix the actual issue.  If the JavaScript submit handler actually ran, the e.preventDefault(); should have stopped the submit.   

    Friday, September 4, 2020 11:15 AM