Reputation: 365
I have an MVC app that I do ajax calls to but I now need to do a post and pass a json object.
I can't seem to get to the web method that passes the jsonString.
I have an ajax call that does a post:
$.ajax({
type: "POST",
async: false,
global: false,
url: uri,
data: "{image:testit}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
json = data;
},
error: function (err) {
console.log('Issue with ajaxPostCallForJson - err: ' + err);
reject('Issue with ajaxPostCallForJson - err: ' + err);
}
});
The web methods are:
[System.Web.Mvc.HttpPost]
public string updateAttachmentToServer()
{
string result = string.Empty;
return result;
}
[System.Web.Mvc.HttpPost]
public string updateAttachmentToServer(string jsonStringWorkIssues)
{
string result = string.Empty;
return result;
}
My routings are:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
It goes to the method that has no parameter but not the one that does, even though my routings have one with a parameter.
Am I missing something?
Thanks.
OK,
I changed the Routing to the following so that the parameter name matches the routing and the ajax call:
[System.Web.Mvc.HttpPost]
public string updateAttachmentToServer(string image)
{
string result = string.Empty;
return result;
}
I added a new routing to handle the new image name:
config.Routes.MapHttpRoute(
name: "ActionApi2", // Route name
routeTemplate: "api/{controller}/{action}/{image}", // URL w/ params
defaults: new { image = RouteParameter.Optional } // Param defaults
);
The ajax call was changed to:
$.ajax({
type: "POST",
async: false,
global: false,
url: uri,
data: { image: '10'}, //"{ modelCode:\"" + $(this).attr('data-model') + "\", vdcCode:\"" + $(this).attr("data-vdc") + "\" }",
dataType: "json",
success: function (data) {
json = data;
},
error: function (err) {
console.log('Issue with ajaxPostCallForJson - err: ' + err);
reject('Issue with ajaxPostCallForJson - err: ' + err);
}
});
But it still goes to the first method - the one with no parameters.
Upvotes: 0
Views: 511
Reputation: 1021
1) dataType: "json", // its mean server return data type
[System.Web.Mvc.HttpPost]
public string updateAttachmentToServer(string image)
{
string result = string.Empty;
return result;
// here return should be json , instead of string
}
2 ) Make sure Url of webapi
3) contentType: "application/json; charset=utf-8", its mean data type send to server , change your data to json first then send to server
data: JSON.stringify({ image: '10'}),
Upvotes: 0