简体   繁体   中英

JQuery Function Ajax method not calling controller in MVC

I have JQuery function to collect all checked romsIds and passing to controller method, but it is not calling the controller method. Controller Name : ApproveURLsController

Here my code :

$("#Approve").click(function () {

    checkedIds = $(".ckb").filter(":checked").map(function () { return this.id; });

    $.ajax({
        type: "POST",
        url: "@Url.Action("ApproveOrRejectAll", "ApproveURLs")",
        traditional: true,
        data: { Ids: checkedIds.toArray() , Status: "A" },
        success: sucessFunc,
        error: errorFunc
    });

    function successFunc(data, status) {

        location.reload();
    }
    function errorFunc(data, status) {

        alert('error');
    }
});

in the above code "Approve" is the button, which I have defined like this

<input type="button" value="Approve" id="Approve" class="btn btn-primary" />

and my controller method

[HttpPost]
public void ApproveOrRejectAll(List<int> Ids, string Status)
{

}

I am not able to find out the problem, kindly help me on this.

Create model to hold desired values.

public class ApproveOrRejectAllModel {
    public List<int> Ids { get; set; }
    public string Status { get; set; }
}

Update action to use defined model

[HttpPost]
public void ApproveOrRejectAll([FromBody]ApproveOrRejectAllModel model) {
    List<int> Ids = model.Ids;
    string Status = model.Status;

    //..other code
}

On client side make sure the data is sent correctly.

$("#Approve").click(function () {

    checkedIds = $(".ckb").filter(":checked").map(function () { return this.id; });

    //Constructing payload to be posted.
    var model = { Ids: checkedIds.toArray(), Status: "A" };

    $.ajax({
        type: "POST",
        url: "@Url.Action("ApproveOrRejectAll", "ApproveURLs")",
        traditional: true,
        data: JSON.stringify(model), //<-- stringify data to be sent.
        success: sucessFunc,
        error: errorFunc
    });

    function successFunc(data, status) {

        location.reload();
    }
    function errorFunc(data, status) {

        alert('error');
    }
});

You cannot call a Non-ActionResult function through HTTP without some workaround.

You either have to embed [WebMethod] above your void ApproveOrRejectAll(...) or change the type to ActionResult.

Use can achieve this using java script array

View:-

<div>
    <input type="checkbox" name="checkBoxHeader" class="checkBoxHeader" value="1" /> 1
    <input type="checkbox" name="checkBoxHeader" class="checkBoxHeader" value="2" /> 2
    <input type="checkbox" name="checkBoxHeader" class="checkBoxHeader" value="3" /> 3
</div>

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Login" class="btn btn-default" id="btnSummit"/>
    </div>
</div>
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    var obj;
    $(".checkBoxHeader").click(function () {
        var checkBoxValueToPush = new Array();

        //checked check box value
        $('.checkBoxHeader:checked').each(function () {
            checkBoxValueToPush.push($(this).val());
        });
        obj = {
            CheckeBoxdIds: checkBoxValueToPush
        };
    });
    $("#btnSummit").click(function () {
        $.ajax({
            url: '/Default/filterData',
            contentType: 'application/json; charset=utf-8',
            type: 'POST',
            data: JSON.stringify(obj),
            cache: false,
            success: function () {
            },
            error: function (xhr, status, error) {
                alert("Error");
            }
        });
    });
</script>

Controller:-

[HttpPost]
        public void filterData(List<int> CheckeBoxdIds)
        {
            // Code
        }

Hope It Work!!!

Happy Coding !!!

Hi as per your code snippet I understand that few of things you missing in you code.I explain one example to call the controller using ajax.

    //Define the type of result you want from you controller here I m describing for JSONResut
    //Controller with 2 parameter's make sure the type and name of parameter  posted is same as written in controller method.
    public JsonResult SaveEmployeeRecord(string id,string name)  
    {  
         string this_id = id;  
         string this_name = name;  
         // do here some operation  
         return Json(new {id=this_id,name = this_name },JsonRequestBehavior.AllowGet);  
}

//View /Javascript to call action method
$.ajax({  
           type: 'POST',  
           dataType: 'json',  
           url: '/Home/SaveEmployeeRecord',  
           data: { id: '67', name: 'Prashant' },  
           success: function (Data) {  
               alert(data.id);  
               alert(data.name);  
           },  
           error: function (XMLHttpRequest, textStatus, errorThrown) {  

           }  
       });  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM