Learner
Learner

Reputation: 351

Not able to call simple web api post method from jquery

Firstly I am unable to pass the model from jquery to my web-api, so I changed my code and write a simple controller with GET and POST

using ContactInfo.Models;
using System.Collections.Generic;
using System.Linq;

using System.Web.Http;
using System.Web.Http.Cors;

namespace ContactInfo.Controllers
{
    [RoutePrefix("api/Contact")]
    public class ContactController : ApiController
    {
        List<ContactDto> contactList = new List<ContactDto>
       {
            new ContactDto { ContactId = 1, ContactName = "x", MobileNumber="1234567890" },
            new ContactDto { ContactId = 1, ContactName = "y", MobileNumber="1234567890" },
       };
        [HttpGet]
        [Route("GetProducts")]
        public IEnumerable<ContactDto> GetAllProducts()
        {
            return contactList;
        }
        [Route("AddProduct")]
        [HttpPost]
        public string Add(string name)
        {
            return name;
        }
    }
}

My HTML is as follows

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>
    <!--<button id="Result" value="Submit" />-->
    <input id="Result" name="Result" type="button" value="Submit" />

    <script type="text/javascript">
        $(document).ready(function () {
            var name = 'hi';
            $("#Result").click(function () {
                $.ajax({
                    url: 'http://localhost:51856/api/Contact/AddProduct',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    type: 'POST',
                    data: name,
                    success: function (response) {
                        alert('hello');
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>

Error I am getting is as follow on submitting the form

"Message":"No HTTP resource was found that matches the request URI 'http://localhost:51856/api/Contact/AddProduct'.","MessageDetail":"No action was found on the controller 'Contact' that matches the request."}

Upvotes: 0

Views: 1389

Answers (1)

artista_14
artista_14

Reputation: 716

Well you are doing it wrong. There are 2 ways to achieve this.

  • 1st Method -

Add a model class StudentModel.cs

public class StudentModel
{
    public string name { get; set; }
}

Then Accept that parameter as Model -

[Route("AddProduct")]
[HttpPost]
public string Add(StudentModel model)
{
    return "";
}

and in Jquery Request ->

var postData = {};
postData.name = "Tom";
$("#Result").click(function () {
            $.ajax({
                url: '/api/Contact/AddProduct',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: 'POST',
                data: JSON.stringify(postData),
                success: function (response) {
                    alert('hello');
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
  • 2nd Method -> pass name as parameter in URl url: '/api/Contact/AddProduct?name=' + name and accept the paramter as string in Action AddProduct (Not Recommended as it is a POST request)

Upvotes: 1

Related Questions