c# error passing a string in POST from jquery to a WebAPI project method

陌路散爱 提交于 2019-12-25 12:09:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!