问题
I'm doing something seemingly easy. I have a jquery function that call a WebApi project method (c# visual studio 2013). This method accept a string in input as parameter.
this is my javascript code
function insert() {
var tag='test';
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded"
url: 'api/TAGS/InsertTAG',
data: tag,
success: function (msg) {
$("#result").html(msg);
},
error: function () {
alert("fail");
}
});
}
WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApiGet",
routeTemplate: "api/{controller}/{action}/{id}/{filter}",
defaults: new { id = RouteParameter.Optional, filter = RouteParameter.Optional }
);
Controller
[HttpPost]
public IHttpActionResult InsertTAG([FromBody] string tag)
{
var da = new TagsDataAccess();
return result = da.InsertTAG(tag);
}
The ajax call is successful but the parameter tag that arrives in InsertTAG is null.
where am I doing wrong?
回答1:
The POST payload should be:
data: '=' + tag,
来源:https://stackoverflow.com/questions/23566614/c-sharp-error-passing-a-string-in-post-from-jquery-to-a-webapi-project-method