如何将数据从jquery发布到webapi(mvc4.0)?

时间:2015-06-25 07:58:44

标签: jquery asp.net-mvc asp.net-web-api

我正在尝试从本地计算机上的跨域调用以下请求。它调用但在服务器端无法在函数参数中找到传递的值。我正在使用MVC4 WebAPI。

$.ajax({
    url: 'http://localhost/webapp1/api/TicketAPI/GetTicketsByFilter',
    type: 'POST',
    dataType: 'jsonp',
    data: { 
        Condition: '2', 
        StartDate: 's', 
        EndDate: 's',    
        Priority: '2', 
        Status: '2', 
        Category: 's',
        PageNumber:1,
        PageSize: 10,
        OrderBy: 's', 
        OrderDir: 'asc' 
    },
    crossDomain: true,
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        debugger;
        alert(data);
        // result = JSON.parse(data.lstRecords);
        // $(result).each(function (e) {
        //     var p = new Date(this["CreatedOnUtc"]);
        //     $("#list").addRowData(e, this);
        // });  
    },
    error: function () {
        alert('fine');
    }
});
}
//below is the serverside code .

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//using System.Web.Mvc;
using CS.Services.Tickets;
using CS.Core;
using System.Data.SqlClient;
using System.Data;
using CS.Services;
using System.Web.Http;
using CS.Web.Utility;
using System.Security.Cryptography;
using System.Configuration;

public TicketSearchResult GetTicketsByFilter(SearchParameter ObjParameter)
{
    //I always found ObjParameter is null .It should have some values
    //some code here/
}

如何在ObjParameter中发布值,使其具有值而不是null。?

 public class SearchParameter
    {
       public SearchParameter()
       {
        PageNumber = 1;
        PageSize = 100;
        OrderBy = "TicketID";
        OrderDir = "ASC";
    }

    public string Condition { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }
    public string Priority { get; set; }
    public string Status { get; set; }
    public string Category { get; set; }
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
    public string OrderBy { get; set; }
    public string OrderDir { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您必须检查您的json对象是否具有SearchParameter类的所有字段(和相同的类型)。

然后,您可以这样打电话:

 $.ajax({
        url: 'http://localhost/webapp1/api/TicketAPI/GetTicketsByFilter',
        type: 'POST',
        data:JSON.stringify({ Condition: '2', StartDate: 's', EndDate:'s',Priority: '2', Status: '2', Category: 's',PageNumber:1,PageSize:10,OrderBy:'s',OrderDir:'asc' }),            
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            //your code
        },
        error: function (x, y, z) {
            alert(x + '\n' + y + '\n' + z);
        }
    });