Home > Net >  How to call onget method with parameters in .net core using ajax
How to call onget method with parameters in .net core using ajax

Time:06-28

I tried to call this onget method in .net core using ajax call but this method hitting without parameters

 public void OnGet(string id,string refundReason ,int amount)
        {           
           
        }

I used these 2 ajax call but not passing parameter values

$.ajax({
    url: "https://localhost:7197/Transactions/Refund?id=" '20a63762-a6ab-4edb-852b-fd247e9dc247' "&refundReason=" refundReason "&amount=" amount,
    type: "GET",       
    data: JSON.stringify({ id: '20a63762-a6ab-4edb-852b-fd247e9dc247',
                           refundReason:'tt',
                           amount:"1"
                        }), 
    dataType: "json",
    traditional: true,
    contentType: "application/json; charset=utf-8",
    success: function (data) {
      debugger;
      
    },
});

this one alse tried not passing values to onget method. let me know what changes i've to do. Thanks

 $.ajax({
        url: "https://localhost:7197/Transactions/,
        type: "GET",       
        data: JSON.stringify({ id: '20a63762-a6ab-4edb-852b-fd247e9dc247',
                               refundReason:'tt',
                               amount:"1"
                            }), 

CodePudding user response:

You should just be able to call it with $.get and passing the values in the query string. GET calls do not accept body data.

$.get(`https://localhost:7197/Transactions/Refund?id=20a63762-a6ab-4edb-852b-fd247e9dc247&refundReason=${refundReason}&amount=${amount}`, response => {
    ...
});

CodePudding user response:

first, your should indicate how you want to get parameters from client. try using [FromQuery], [FromBody], [FromForm] attiributes on your parameters and also you need specify your request method [HttpGet], [HttpPost] etc.

second, in the code you posted you send data from body and also fromquery. you need use one of them.

this should work

 [HttpGet]
 public void OnGet([FromQuery]string id,[FromQuery]string refundReason , 
   [FromQuery]int amount)

in the ajax code remove data section.

and please be sure you are giving right url parameter to ajax code

  • Related