Asbah Qadeer
Asbah Qadeer

Reputation: 61

Call JQuery function through Web API Controller

I went through many posts but none exactly targeted a Web API Controller in the MVC Framework so I had to write a post regarding this.

I am using C# and my controller action looks something like this:

//[HttpGet]/[HttpPost]/etc.. anything can be here
    public IEnumerable<something> Customers()
    {
     //Code
        return List;
    }

And my script in my cshtml view file looks something like below:

@section scripts
{
<script type="text/javascript">

</script>
}

Now if I want to call a jquery function and/or pass some data to it as well on the client side from my C# code, what would my action and jquery code look like?

Upvotes: 0

Views: 995

Answers (1)

Adrian
Adrian

Reputation: 8597

Your MVC controller should look like similar to this...

public class ExampleController
{

    [HttpGet]
    public ActionResult Customers(string nameParameter)
    {
        //Code
        return Json(nameParameter);
    }
}

You need to define the accepted parameters in the functions constructor.

Your Ajax call on the other hand...

$.ajax({
  url: "/Example/Customers?nameParameter=Asbah",
  success: function(html){
    // Returned value
  }
});

The parameters need to match the names you defined in your function constructor. Note in the URL /Example/ it refers to ExampleController.

Upvotes: 1

Related Questions