Ajax passing data to ASP.NET controller

Viewed 500

I'm attempting to run an ajax request on my ASP.NET web app where I pass a search term and receive some data back

<div class="form-group">
           <input type="text" id="orgSearch" placeholder="Search organisation by name..." class="form-control" name="search" autocomplete="off" data-controller="@Model.ControllerName" data-target-property="@Model.LookaheadProperty">
</div>
<script>
    $(document).ready(function () {
        var form = document.getElementById("orgSearch");
        form.addEventListener("keyup", function (event) {
            event.preventDefault();
            var search = document.getElementById("orgSearch").value;
            $.ajax({
                type: "GET",
                url: "Organisation/Search?search=" + search,
                success: function (object) {
                    console.log(object);
                }
            });
        });

    });

</script>

And then here's the method in my OrganisationsController.cs class


public class OrganisationsController : Controller
{
        [HttpGet]
        public async Task<IActionResult> Search([FromRoute] string search)
        {
            var items = await _organisationsService.SearchAsync(search);

            return Ok(items);
        }
}

However, when I try it the ajax call isn't even being made (It's generating a 404 error on the console log) and I can't work out how to pass the search parameter. Does anyone have any suggestions?

1 Answers

Fix ajax url from organization to organizations and add "/" in the beginning:


 url: "/Organisations/Search?search=" + search,

your action then

 public async Task<IActionResult> Search([FromQuery] string search)
        {
            ......
        }

You can also try to use [FromUri] instead [FromQuery]

And by the way, if your version Mvc supports attribute routing, it maybe better to change action to this:

        [Route("~/Organizations/Search/{search}")]
        public async Task<IActionResult> Search( string search)
        {
            ....
        }

in this case your ajax url:

url: "/Organisations/Search/" + search,
Related