将Javascript对象数组传递给MVC控制器

时间:2018-09-11 01:14:32

标签: javascript c# jquery asp.net

我有这些ViewModel:

public class UserAddRoleListViewModel
{
    public String Id { get; set; }
    public String Name { get; set; }
}

public class SaveUserNewRoleViewModel
{
    [Required]
    public String RoleId { get; set; }
    public String RoleName { get; set; }
    public List<UserAddRoleListViewModel> RoleList { get; set; }
}

如何传递具有以下格式的对象数组:

var object = {
    Id: rowIdItem,
    Name: rowItem
};

dataSet.push(对象);

到我的MVC控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VerifyRole(SaveUserNewRoleViewModel Input)
    {
        IEnumerable<object> errors = null;
        if (ModelState.IsValid)
        {
            if(Input.RoleList[0] != null)
            {
                foreach (var item in Input.RoleList)
                {
                    if (Input.RoleId == item.Id)
                    {
                        ModelState.AddModelError("RoleId", "Role already exists");
                        errors = AjaxError.Render(this);
                        return Json(new { success = false, errors });
                    }
                }
                return Json(new { success = true });
            }
            return Json(new { success = true });
        }
        else
        {
            errors = AjaxError.Render(this);
            return Json(new { success = false, errors });
        }
    }

到目前为止,似乎在调试时它总是不传递任何信息

编辑:

仅作澄清。我已经可以通过ajax传递该项目。只是当我调试时,RoleList为空。

这是我的ajax函数:

$(document).on("submit", "#modal", function (e) {
        e.preventDefault();
        var selectedText = $("#@Html.IdFor(m=>m.RoleId) :selected").text();
        var selectedId = $("#@Html.IdFor(m=>m.RoleId)").val();
        var form_data = $(this).serializeArray();
        form_data.push({ name: "RoleList", value: dataSet });
        console.log(form_data);
        rowIdItem = selectedId;
        rowItem = selectedText;
        $("#close").trigger("click");
        $.ajax({
            url: "@Url.Action("VerifyRole", @ViewContext.RouteData.Values["controller"].ToString())",
            method: "POST",
            data: form_data,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            success: function (result) {
                if (result.success) {
                    rowIdItem = selectedId;
                    rowItem = selectedText;
                    $("#close").trigger("click");
                    return;
                }
                $.each(result.errors, function (index, item) {
                    // Get message placeholder
                    var element = $('[data-valmsg-for="' + item.propertyName + '"]');
                    element.empty();
                    // Update message
                    element.append($('<span></span>').text(item.errorMessage));
                    // Update class names
                    element.removeClass('field-validation-valid').addClass('field-validation-error');
                    $('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
                });
            }
        });
        return false;
    });

编辑2:

添加了填充dataSet的代码:

$(document).on($.modal.AFTER_CLOSE, function (event, modal) {
    dataSet.push(object);
    table.row.add(object).draw();
    $("#modal").empty();
});

2 个答案:

答案 0 :(得分:0)

JavaScript

$("#myBtn").click(function () {

                var dataSet= [];
                var obj = {
                              Id: rowIdItem,
                              Name: rowItem
                         };
                dataSet.push(obj);

                var data = {
                "RoleId": '1',
                "RoleName ": 'roleName',
                "RoleList": dataSet
                };

                $.ajax({
                    type: "POST",
                    traditional:true,
                    url: "controller/VerifyRole",
                    content: "application/json;",
                    dataType: "json",
                    data: data ,
                    success: function () {
                    }
                });
            });

控制器/操作

[HttpPost]
public ActionResult VerifyRole(SaveUserNewRoleViewModel input)
{
    ...
}

答案 1 :(得分:0)

尝试一下:)

$(document).on("submit", "#modal", function (e) {
    e.preventDefault();
    var selectedText = $("#@Html.IdFor(m=>m.RoleId) :selected").text();
    var selectedId = $("#@Html.IdFor(m=>m.RoleId)").val();
    var form_data = {};
    form_data.RoleId = selectedId;
    form_data.RoleName =selectedText;
    console.log(form_data);
    rowIdItem = selectedId;
    rowItem = selectedText;
    $("#close").trigger("click");
    $.ajax({
        url: "@Url.Action("VerifyRole", @ViewContext.RouteData.Values["controller"].ToString())",
        method: "POST",
        data: JSON.stringify(form_data),
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        success: function (result) {
            if (result.success) {
                rowIdItem = selectedId;
                rowItem = selectedText;
                $("#close").trigger("click");
                return;
            }
            $.each(result.errors, function (index, item) {
                // Get message placeholder
                var element = $('[data-valmsg-for="' + item.propertyName + '"]');
                element.empty();
                // Update message
                element.append($('<span></span>').text(item.errorMessage));
                // Update class names
                element.removeClass('field-validation-valid').addClass('field-validation-error');
                $('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
            });
        }
    });
    return false;
});

我的数据集示例:

  $("body").on("click", "#btnSave", function () {
    var ops = new Array();
    $("#table TBODY TR").each(function () {
        var row = $(this);
        var ps = {};
        ps.colname1 = row.find("TD").eq(0).html();
        ps.colname2 = row.find("TD").eq(1).html();
        ps.colname3=  row.find("TD").eq(2).html();
        ops.push(ps);
    });
    var item = {};
    item.nam1 = "test";
    item.List = ops;
     $.ajax({
        type: "POST",
        url: " ...",
        data: JSON.stringify(item),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {

        }
    });
});