0

I have below asp.net service :

[ActionName("AddNewCompany")]
public apiResult UpdateCompany(Company company, string UserCode, string APIKey)
{
  spCard myStoreProcedure = new spCard();
  return myStoreProcedure.updateCompany(company, UserCode, APIKey);
}

i try to use $.ajax call above service, i keep received error message 'Not Found'

    var apiParameter = {
        Code: code,
        Name: name,
        CompanyGroup: companyGroup
    };
    request = $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: G_BASE_URI + "testAPI/AddNewCompany",
        data: "company=" + JSON.stringify(apiParameter) + "&UserCode=AAA&APIKey=123"
    });

i change the $.ajax to below, still getting 'Not Found'

    var apiCompany = {
        Code: code,
        Name: name,
        CompanyGroup: companyGroup
    };
    var apiParameter = { company: apiCompany, UserCode: "XXX", APIKey: "12345" };

    request = $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: G_BASE_URI + "dbCard/AddNewCompany",
        data: jQuery.param(apiParameter)
    });

i have other services which only have 1 parameter, it work as expected. For those services more than 1 parameter. i am facing this problem.

1 Answer 1

1

For the C# model binder to effectively map the values you send you would be better to provide the data in an object which you can structure it to exactly match the properties of your class.

Note that in your current code you set dataType to JSON, yet you send a form-urlencoded string. Try this:

var data = {
    company: {
        Code: code,
        Name: name,
        CompanyGroup: companyGroup
    },
    UserCode: 'AAA',
    APIKey: '123'
};

request = $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: G_BASE_URI + "testAPI/AddNewCompany",
    data: data
});

Also note that by providing an object directly to the data property of $.ajax jQuery will encode and escape the values for you, as necessary.

Sign up to request clarification or add additional context in comments.

1 Comment

i try to avoid create many class for this purpose. Finally i decide to change the parameter to type 'string jsonObject' and in client, will use JSON.stringify to convert object into json and pass to server. on server site, will convert this json string to dynamic object and use it. with this method, i can skip the create object class for the parameter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.