-1

I am unable to post data from view page to Wep Api MVC 4 . My Application and Web Api both are different project.

Given below is my jquery ajax call:

   $.ajax({
        url: 'http://localhost/api/Contacts',
        type: 'POST',
        value: 'newcontact',
        dataType: 'jsonp',
        success: function (result) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            debugger;
            alert(errorThrown);
        }
    });

I want to post data from jquery call to below controller method

       // POST api/contacts
    public void Post([FromBody]string value)
    {

    }

Please I am not using models to store data in view page and retrieve them in controller method because both are different project. Moreover its a simple html page in my MVC Project. So Please tell me where I made mistake and tell how to post data from page to Web Api MVC 4?

4

3 回答 3

1

如果您的 Web API 和 Web APPLCATION 不在同一个站点中,那么 JQuery 将不允许 Ajax 调用,因为 Web 浏览器不允许“跨域 Ajax”。

当您使用 Ajax 时,每个请求都必须在同一个站点中完成。(相同的域和端口)

于 2013-08-09T10:23:14.107 回答
0

您需要在data参数中传递变量,如下所示:

$.ajax({
    url: 'http://localhost:50043/api/Contacts',
    type: 'POST',
    data: { 'value': 'newcontact' }, // parameters to pass go in to this object
    dataType: 'jsonp',
    success: function (result) {
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        debugger;
        alert(errorThrown);
    }
});

假设 URL 是正确的,以上将起作用。

于 2013-08-09T09:32:01.587 回答
0

您需要使用data参数:

$.ajax({
        url: 'http://localhost:50043/api/Contacts',
        type: 'POST',
        data:
        {
            value: 'newcontact'
        },
        dataType: 'jsonp',
        success: function (result) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            debugger;
            alert(errorThrown);
        }
    });

而且,因为您的 ajax 请求类型是POST,所以您必须为您的操作添加[HttpPost]属性:

[HttpPost]
public void Post(string value)
{

}

编辑

要获取错误消息,请使用以下命令:

error: function (xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    }
于 2013-08-09T09:30:59.763 回答