如果api传递复杂数据以获取调用

时间:2016-11-04 03:35:31

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

我正在尝试传递一个viewmodel数据以在web api中调用..

这里是viewmodel属性

public class FilterViewModel
{
    public int RegionID { get; set; }

    public int StateID { get; set; }

    public int DistrictID { get; set; }

    public int UniversityID { get; set; }

    public int CollegeID { get; set; }

    public DateTime FromDate { get; set; }

    public DateTime ToDate { get; set; }
}

这是我想要的ajaxcall ..

  

将formdata转换为json对象

function toSimpleJson() {

    });
    return json;
}
  the ajax call
function GetFilteredRecords() {

var filterOptions = toSimpleJson();

$.ajax({
    url: '/api/workassign',
    data: JSON.stringify(filterOptions),
    cache: false,
    type: 'GET',
    dataType: 'JSON',
    success: function (data) {
        debugger
    }
});

}

这里是filteroptions数据

enter image description here

  

这是api控制器获取动作

public IEnumerable<WorkAssignViewModel> Get([FromUri]FilterViewModel date)
    {

    }

这里我将表单数据转换为json对象并使用建议的json.stringify()传递给控制器​​,并在控制器中使用[FROMUri],但仍然值为null ......

请告诉我一个克服的解决方案

谢谢..

1 个答案:

答案 0 :(得分:1)

您需要删除JSON.stringify() and contentType from the ajax call. You making a GET and a GET does not have a body (therefore contentType`选项是没有意义的)。你编码ajax调用应该是

$.ajax({
    url: '/api/workassign',
    data: filterOptions,
    cache: false,
    type: 'GET',
    dataType: 'JSON',
    success: function (data) {
        debugger
    }
});

请注意,您是否已根据具有@model FilterViewModel的视图正确生成表单控件并使用HtmlHelper方法生成表单控件(@Html.TextBoxFor(m => m.RegionID)等),然后您可以简单地使用data: #('form').serialize(),