Rahul Nagrale
Rahul Nagrale

Reputation: 93

How to pass parameter from Ajax Request to Web API Controller?

I am looking for the way to pass the parameter from Ajax Request to Web API Controller in ASP.Net Core like query string in classic ASP. I have tried below but it did not worked.

View:

"ajax":
    {
        "url": "/api/APIDirectory/[email protected]"
        "type": "POST",
        "dataType": "JSON"
    },

Controller:

[HttpPost]
public IActionResult GetDirectoryInfo(string reqPath)
{   
    string requestPath = reqPath;
    // some code here..
}

Can anyone please advise the ways available to achieve this in asp.net core web api?

Upvotes: 1

Views: 9668

Answers (3)

I did few things to call an API(server) from AJAX call(Client) Here is my code The API controller action:

[Route("Create")] //POST
    [HttpPost]
        public ActionResult Create(string StudentName, int age, string Address)
        {
            try
            {
                 //Your code here
                return Ok(new { Message = "Record Added" });
            }
            catch (Exception ef)
            {

                return BadRequest(ef.Message);
            }
        }

The Client ajax call:

function SaveData() {
                debugger;
                var n = $('#StudentName').val();
                var a = parseInt($('#age').val());
                var ad = $('#Address').val();
                $.ajax({
                    type: 'POST',
                    url: 'http://localhost:5128/api/Students/Create?StudentName='+n+'&age='+a+'&Address='+ad,
                    contentType: 'json',
                    //data: { studentName: n, age:a , address:ad},
                    success: function (response) {
                        if (response.length == 0) {
                            alert(response);
                        } else {
                            alert("Data Saved!");
                            };
                        },
                    error: function (err) {
                        console.error(err);
                    }
               });
            }

Upvotes: 0

Nagarajan Sampath
Nagarajan Sampath

Reputation: 26

"ajax":
{
    "url": "/api/APIDirectory/GetDirectoryInfo"
    "type": "POST",
    "dataType": "JSON",
    "data": {"reqPath":"@ViewBag.Title"}
}

Edited: If we use query string, we can use the type as GET.

But we are using POST method, so we need to pass the data with the param "data".

Upvotes: 1

Marcus Höglund
Marcus Höglund

Reputation: 16801

When posting data in query string use the content type application/x-www-form-urlencoded

$.ajax({
  type: "POST",
  url: "/api/APIDirectory/GetDirectoryInfo?reqPath=" + @ViewBag.Title,
  contentType: "application/x-www-form-urlencoded"
});

Also, make sure that the ajax syntax is correct (I use jQuery in my example) and that the @ViewBag is not included in the string.

Then add the [FromUri] parameter in the controller to make sure the binding reads from the uri

[HttpPost]
public IActionResult GetDirectoryInfo([FromUri]string reqPath)
{   
    string requestPath = reqPath;
    // some code here..
}

Upvotes: 1

Related Questions