【问题标题】:pass complex data to get call if api如果 api 传递复杂数据以获取调用
【发布时间】:2017-03-17 19:51:31
【问题描述】:

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

这里是视图模型属性

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 ..

将表单数据转换为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
    }
});

}

这是过滤选项数据

这里是 api 控制器获取操作

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

    }

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

请给我一个解决方案来克服

谢谢你..

【问题讨论】:

  • filterOptions的值是什么,FilterViewModel的属性是什么? (注意设置 contentType 选项是没有意义的 - 它是一个 GET 并且没有正文)
  • @StephenMuecke 感谢您的回复,我添加了属性和过滤选项数据..
  • 只需使用data: filterOptions, (并且由于您似乎已经正确生成了视图(至少基于您所展示的少量内容,您可以删除您的toSimpleJson() 函数并使用data: $('form').serialize(),
  • @StephenMuecke 删除 json.stringify() 后工作正常.. 非常感谢..

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2018-07-07
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多