0
votes

Here is my js code to call custom web api method..

$.ajax({
        url: '/api/AdminAPI/IndustryPost/?industryName='+addNewIndustryName,
        type: 'Post',
        cache: false,
        contentType: 'application/json; charset=utf-8',       
        success: function (response) {
           // response code.
        }
    });

this is working fine but in case i am using 'data' tag to send data, its not working. like THE FOLLOWING.

 $.ajax({
        url: '/api/AdminAPI/IndustryPost',
        type: 'Post',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        data: { 'industryName': addNewIndustryName },
        success: function (response) {
           // response code.
        }
    });

WebApiConfig is config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{action}/{id}",
             defaults: new { id = RouteParameter.Optional }
        );

here is my api method

    [ActionName("IndustryPost")]
    public void AddIndustry(string industryName)
    {
        //code here
    }

While testing with fiddler second code request result to 404 error. While accessing web API method directly from URL works fine.

Answer::

After doing R'N'D on this topic i came to know that there is a issue in web API parameter binding. So, what either we can use [formUri] tag or we can have a model class. like this

public class IndustryName { public string Industryname { get; set; } }

and in web api method

public void IndustryPost(IndustryName industryName) { // }

No change needed in jquery.

Here this article explain it all Post int as part of method but get No HTTP resource was found that matches the request URI error

2

2 Answers

0
votes

change below line

data: { 'industryName': addNewIndustryName }

to

data: '{ industryName:'+ addNewIndustryName +'}'

and also make sure that, addNewIndustryName is global variable and accessible.

Or you can simply assign variable without curly braces like below

data: 'industryName='+ addNewIndustryName
0
votes

here you are missing a quote in your ajax url:

$.ajax({
    url: '/api/AdminAPI/IndustryPost/', //<----here put a / slash at the end
    type: 'Post',
    cache: false,
    dataType: 'json', //<-------you can use json
    contentType: 'application/json; charset=utf-8',
    data: { 'industryName': addNewIndustryName },
    success: function (response) {
       // response code.
    }
});