【问题标题】:Post a list of objetcs and an int into a Core MVC Controller with jQuery Ajax使用 jQuery Ajax 将对象列表和 int 发布到 Core MVC 控制器中
【发布时间】:2018-05-31 09:49:01
【问题描述】:

我正在尝试使用 jQuery Ajax 帖子将对象数组和 int 传递到 Core MVC 控制器。

我已经看到了很多很多关于这个问题的答案,但我没有找到适合我的答案......似乎使用 Core MVC 不像经典 MVC 那样工作。

对象类:

public class Field : Nameable //herit of the ID and Name properties
{
    public string Value { get; set; }

    public Field () { }
}

MVC 控制器功能:

[HttpPost]
public JsonResult SaveFields(List<Field> fields, int id)
{
   return Json(new { success = true, responseText = "OK" });
}

jQuery 函数:

$('#btnSaveFields').click(function () {
    var $rows = $('#table').find('tr:not(:hidden)');
    var data = [];
    var id = 1;

    // Turn all existing rows into a loopable array
    $rows.each(function () {
        var $td = $(this).find('td');
        var obj = new Object();
        obj.ID = $td.eq(0).children().attr('value');
        obj.Name = $td.eq(0).text().trim();
        obj.Value= $td.eq(1).text();
        data.push(obj);
    });
    data.shift(); // don't take the headers row
    console.log(data[0]); //seems ok
    var fields = JSON.stringify({ 'fields': data });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: '@Url.Action("SaveFields")',
        //traditional: true, //don't work or wrong use ?
        type: 'POST',
        data: {
            'fields': fields,
            'id' : id
        },
        success: function (response) {
            console.log('ok')
        },
        error: {
            console.log('nok')
        }

    });
});

MVC 控制器函数调用有效,但参数为空。你知道我做错了什么吗?

【问题讨论】:

    标签: jquery ajax asp.net-core asp.net-core-mvc


    【解决方案1】:

    我找到了解决问题的方法!

    这只是我的打字错误。 contentType 的“C”必须大写。

    答案:

    $.ajax({
            url: '@Url.Action("SaveFields")',
            ContentType: 'application/json',
            dataType: 'json',
            type: 'POST',
            data: { fields: data, id: id },
            success: function (response) {
                console.log('OK')
            },
            error: function (){
                console.log('NOK');
            }
    
        });
    

    【讨论】:

    • 完全废话-阅读documentation-它的contentType-小写c
    • 我不知道为什么,但它有效。我没有改变其他任何东西。
    • 如果你这样做了,这意味着你将数据作为默认 'application/x-www-form-urlencoded; charset=UTF-8' 发送,这意味着你在问题中显示的代码不可能工作
    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多