0

Hello I am trying to call a method with parameters in my controller using ajax and jquery

Controller:

[HttpPost("{Id}")] 
public ActionResult PostComment(int Id, ShowViewModel model)
{
}

View:

I have a button called AddComment, when clicked it should open a modal popup which asks for confirmation to save

<form id="addCommentForm" asp-action="postcomment" enctype="multipart/form-data">
    <button id="addCommentButton" class="btn btn-primary">
        <i class="fa fa-search"></i>&nbsp;Add comment
    </button>`

    <div class="modal fade" id="saveConfirmationDialog" tabindex="-1" role="dialog" aria-labelledby="saveConfirmationDialogTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="saveConfirmationDialogTitle">Post selective exchange comment</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    Do you want to post a comment?
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">
                        <i class="fa fa-envelope-open"></i>&nbsp;Post selective exchange comment
                    </button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal">
                        <i class="fa fa-ban"></i>&nbsp;Close
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

Javascript:

ControllerName.View.Properties.controllerViewUrl = $("#controllerViewUrl").val();

    $(document).ready(function () {
        ControllerName.View.Validation.initialize();
        ControllerName.View.Initialize.addCommentButton();
    });

    ControllerName.View.Initialize = {}
    ControllerName.View.Initialize.addCommentButton = function () {
        $('#addCommentButton').click(function (event) {
            event.preventDefault();
            if ($('#addCommentForm').valid()) {
                $("#saveConfirmationDialog").modal('show');
            }
        });
    }


    ControllerName.View.Validation = {}

   ControllerName.View.Validation.initialize = function () {

        $("#addCommentForm").validate();
    }

   ControllerName.View.Ajax = {}

    ControllerName.View.Ajax.postComment = function (successCallback) {
        var url = ControllerName.View.Properties.controllerViewUrl + '/PostComment'+<<parameter>>;
    }

My Controller method is not getting called, what am I doing wrong? I also need to pass a Id as parameter

Please help, Thanks in advance

Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37
Divya
  • 1
  • 1
  • No, i do not have any errors – Divya Apr 19 '18 at 12:22
  • Could you please have a look at my answer on **[Can't call function using ajax](https://stackoverflow.com/questions/36922704/cant-call-function-using-ajax/36924707#36924707)** page and inform me if it works or not? – Murat Yıldız Apr 19 '18 at 12:28
  • There is also another approach on [How to pass selected files in Kendo Upload as parameter in ajax request](https://stackoverflow.com/questions/35178662/how-to-pass-selected-files-in-kendo-upload-as-parameter-in-ajax-request/35200162#35200162) page. Hope this helps... – Murat Yıldız Apr 19 '18 at 12:29

1 Answers1

0

A simple example

HTML CODE

<button id="saveButton" type="button" data-toggle="modal" data-target="#saveConfirmationDialog" class="btn btn-labeled btn-danger" style="display:none;">Save Data</button>
<div id="saveConfirmationDialog" class="modal fade" role="dialog" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 id="modal-title" class="modal-title">Post selective exchange comment</h4>
            </div>
            <div class="modal-body">
                Do you want to post a comment?
            </div>
            <div class="modal-footer">
                <div id="formDiv">
                    <button id="sender" type="submit" class="btn btn-success"><i class="fa fa-envelope-open"></i>&nbsp;Post selective exchange comment</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-ban"></i>&nbsp;Close</button>
                </div>
                <div id="loadingPanel" style="display:none;">Loading...</div>
            </div>
        </div>
    </div>
</div>

JS CODE

<script type="text/javascript">
    $('#sender').click(function () {
        PostDataToController();
    });

    function PostDataToController(action) {
        $('#formDiv').hide();
        $('#loadingPanel').show();
        // create form data
        var formData = new FormData();
        formData.append("YourParameter", $('#YourValue').val());
        // Write here your parameters what you need

        // do post
        $.ajax({
            type: "POST",
            url: "/localhost:8080/InsertComment",
            enctype: "multipart/form-data",
            cache: false,
            contentType: false,
            processData: false,
            data: formData,
            success: function (d) {
                $('#formDiv').show();
                $('#loadingPanel').hide();
                if (d.result == "ok") {
                    /*Your success operations*/
                }
                else {
                    //alert(d.msg);
                    /*Your custom error operations*/
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                /*Your error operations*/
                //alert(xhr);
                $('#formDiv').show();
                $('#loadingPanel').hide();
            }
    });
}
</script>

MVC CODE

[HttpPost]
public ActionResult InsertComment(int Id, ShowViewModel model)
{
    if (ModelState.IsValid)
    {
        // insert
        // Yor save method is here
        if (!isSuccess()) // your process not succeeded
        {
            // error
            return Json(new { result = "no", msg = /*your error message*/ });
        }
        //succeeded
        return Json(new { result = "ok" });
    }
    else
    {
        // error
        string error = ModelState.Values.FirstOrDefault(f => f.Errors.Count > 0).Errors.FirstOrDefault().ErrorMessage;
        return Json(new { result = "no", msg = error });
    }
}