0

I have these ViewModels:

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; }
}

How can I pass an array of objects that have a format like this:

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

dataSet.push(object);

to my MVC Controller here:

    [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 });
        }
    }

So far it seems like its always passing an nothing when I debug it

EDIT:

Just to clarify. I can already pass the item via ajax. It's just that when I debug, RoleList is empty.

This is my ajax function:

$(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;
    });

EDIT 2:

Added code that fills dataSet:

$(document).on($.modal.AFTER_CLOSE, function (event, modal) {
    dataSet.push(object);
    table.row.add(object).draw();
    $("#modal").empty();
});
6
  • You want pass dataSet to VerifyRole method ? Commented Sep 11, 2018 at 3:14
  • @Hossein yeah thats what I wanted Commented Sep 11, 2018 at 4:22
  • If you need check role is exist or not , must get roles list from db and do it in action, because might someone insert/update data in this period. Commented Sep 11, 2018 at 4:48
  • The roles list is already from the db. I just want to check if my new object already exists in the dataSet that is being sent Commented Sep 11, 2018 at 4:58
  • 1
    Where you fill dataSet ? Commented Sep 11, 2018 at 5:06

2 Answers 2

1

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 () {
                    }
                });
            });

Controller/Action

[HttpPost]
public ActionResult VerifyRole(SaveUserNewRoleViewModel input)
{
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

But i'm already doing this. I need to know if my viewmodel is correct?
I added my ajax code. I'm not sure if my viewmodel is correct because when my ajax sends data, the list is empty the second time i add an item even though an item already exists
0

Try this:)

$(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;
});

my example with datasets:

  $("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) {

        }
    });
});

1 Comment

Hi, I need to pass my antiforgerytoken and dataset through as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.