Ajax请求Post Params

时间:2016-03-31 08:23:41

标签: javascript ajax asp.net-mvc ajax-request

我想使用ajax post请求,但我的请求仅在我使用Get请求时有效。

当我使用Get Request时,我的模型被正确填充。使用post请求我的模型为空。

这样可行:

self.ClearRegimeFromUntil = function () {
    var model = { clearFrom: kendo.format("{0:dd/MM/yyyy hh:mm:ss tt}", self.clearFrom()), clearUntil: kendo.format("{0:dd/MM/yyyy hh:mm:ss tt}", self.clearUntil()), userId: self.UserID() };
    console.log(model);
    $.ajax({
        type: "GET",
        url: rootUrl + "api/CalendarDays/ClearRegimeFromUntil",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: model,
        success: function (response) {
            console.log(response);

        }
    });
};

在控制器端:

    [System.Web.Http.HttpGet]
    [System.Web.Http.Route(@"api/CalendarDays/ClearRegimeFromUntil")]
    public async Task<IHttpActionResult> ClearRegimeFromUntil([FromUri] DeleteFromModel model)
    {

        //await _userCalendarDayRepository.DeleteFutureUserCalendarDays(model.UserId,DateTime.Parse( model.ClearFrom));
        return Ok(true);
    }

但这不起作用:

self.ClearRegimeFromUntil = function () {
    var model = { clearFrom: kendo.format("{0:dd/MM/yyyy hh:mm:ss tt}", self.clearFrom()), clearUntil: kendo.format("{0:dd/MM/yyyy hh:mm:ss tt}", self.clearUntil()), userId: self.UserID() };
    console.log(model);
    $.ajax({
        type: "POST",
        url: rootUrl + "api/CalendarDays/ClearRegimeFromUntil",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: model,
        success: function (response) {
            console.log(response);

        }
    });
};

在控制器端:

    [System.Web.Http.HttpPost]
    [System.Web.Http.Route(@"api/CalendarDays/ClearRegimeFromUntil")]
    public async Task<IHttpActionResult> ClearRegimeFromUntil([FromUri] DeleteFromModel model)
    {

        //await _userCalendarDayRepository.DeleteFutureUserCalendarDays(model.UserId,DateTime.Parse( model.ClearFrom));
        return Ok(true);
    }

我的模特:

public class DeleteFromModel
{
    public string UserId { get; set; }
    public string ClearFrom { get; set; }
    public string ClearUntil { get; set; }

}

标题和响应(不知道如何更好地展示它们): http://pastebin.com/AM6ScEsz

2 个答案:

答案 0 :(得分:1)

删除[FromUri]将解决问题。

[System.Web.Http.HttpPost]
[System.Web.Http.Route(@"api/CalendarDays/ClearRegimeFromUntil")]
public async Task<IHttpActionResult> ClearRegimeFromUntil(DeleteFromModel model)
{

    //await _userCalendarDayRepository.DeleteFutureUserCalendarDays(model.UserId,DateTime.Parse( model.ClearFrom));
    return Ok(true);
}

答案 1 :(得分:0)

检查您的html表单是否在POST中

<form method="post">
...
</form>

您能否将您的网络标头和ajax请求的响应发送给我们?