vendredi 16 août 2019

How to pass Array of checkbox data attributes as IEnumeration of Model from jQuery Ajax to the MVC 5 Action?

Long time developer new to JQuery, MVC, & C#

I have a list of a Model (RZRCheckBoxModel) that include values to be displayed as check boxes.

I need to retrieve all the checkboxes regardless of checked state and update a database based on the data- attributes and checked state of the the check boxes

For reasons I won't go into I can't submit the form to retrieve the Model

I am able to retrieve all the checkboxes from the View in JQuery and format them as an array of the Model. However, the ajax call to the control never reaches the action and I don't receive an error

I've been all over Stack Overflow and the internet in general with no luck. I feel like I'm close, I just can't quite put my finger on what needs to be done.

MODEL

public class RZRCheckBoxListModel
    {
        public List<RZRCheckBoxModel> CheckBoxList { get; set; } = new List<RZRCheckBoxModel>();

        public List<RZRCheckBoxModel> JQueryList { get; set; } = new List<RZRCheckBoxModel>();
    }

public class RZRCheckBoxModel
    {
        public int Id { get; set; }

        [Display(Name = "Check Box Name")]
        [Required(ErrorMessage = "Enter a {0}")]
        public string Name { get; set; } = "";

        [Display(Name = "Is Checked")]
        public bool IsChecked { get; set; } = false;
    }

DISPLAY VIEW

This view displays the check boxes on load of the website

@model TestProjects.Models.RazorControls.RZRCheckBoxListModel

            <h5>Data Enty</h5>
            for (int i = 0; i < Model.CheckBoxList.Count(); i++)
            {
                <div class="row">
                    <div class="col-6">
                        @Html.HiddenFor(m => m.CheckBoxList[i].Id)
                        @Html.HiddenFor(m => m.CheckBoxList[i].Name)
                        @Html.CheckBoxFor(m => m.CheckBoxList[i].IsChecked, new { @class = "check-box m-2", data_id = Model.CheckBoxList[i].Id, data_name = Model.CheckBoxList[i].Name})
                        @Html.DisplayFor(m => m.CheckBoxList[i].Name, new { htmlAttributes = new { @class = "control-label m-2" } })
                    </div>
                </div>
                <input type="submit"
                       value="Fake button" 
                       class="btn btn-default" 
                       data-counter="@Model.CheckBoxList.Count()"
                       onclick="javascript: RZRCheckBoxList(this);" />
            }

JQUERY

function RZRCheckBoxList(cntrl) {

    var list = [];
    list.push($('.check-box:Checkbox'));

    var result = [];
    for (var i = 0; i < list[0].length; i++) {
        var RZRCheckBoxModel = {};
        RZRCheckBoxModel.Id = parseInt(list[0][i].attributes["data-id"].value);
        RZRCheckBoxModel.Name = list[0][i].attributes["data-name"].value;
        RZRCheckBoxModel.IsChecked = list[0][i].checked;
        result.push(RZRCheckBoxModel);

    }
var postData = { values: result };
    $.ajax({
        url: baseUrl + 'TestControlsRazorController/RZRJqueryChkBoxList',
        type: 'POST',
        //data: JSON.stringify({ 'MyModel': postData.values }),
        data: JSON.stringify({ 'MyModel': postData }),
        datatype: 'json',
        contentType: "application/json",
        traditional: true,
        success: function (data) {
            var $div = $('#JqueryResults');
            $div.html(data);
        },
        error: function (response, error, message) {
            //populate the error div
            var tst = 'test';

            var msg = "";
            msg += 'Javascript (RZRCheckBoxList): ';
            msg += { 'Error {0} - ': err.toString() };
            msg += { 'Message {0} - ': message.toString() };
            msg += { 'Response {0} ': response.responseText };

            alert(msg);//'JavaScript Error (RZRCheckBoxList): ' + error.toString() + ' - ' + message.toString() + - + response.responseText);
            alert(error + ' - ' + message + ' - ' + response);
        }
    });
}

JSON.stringify({ 'MyModel': postData })

produces the below results


    {
        "MyModel":
        {
            "values":
            [
                {
                    "Id": 0,
                    "Name": "Check Box 1",
                    "IsChecked": false
                },
                {
                    "Id": 1,
                    "Name": "Check Box 2",
                    "IsChecked": true
                }
            ]
        }
    }


JSON.stringify({ 'MyModel': postData.values })

produces the below results

    {
        "MyModel":
        [
            {
                "Id": 0,
                "Name": "Check Box 1",
                "IsChecked": false
            },
            {
                "Id": 1,
                "Name": "Check Box 2",
                "IsChecked": true
            }
        ]
    }

CONTROLLER ACTION

The ajax call never gets here

        //public JsonResult RZRJqueryChkBoxList([FromBody] List<RZRCheckBoxModel>[] MyModel)
        //public JsonResult RZRJqueryChkBoxList(List<RZRCheckBoxModel> MyModel)
        [HttpPost]
 public JsonResult RZRJqueryChkBoxList(RZRCheckBoxModel[] MyModel)
        {
            List<RZRCheckBoxModel> mdl = new List<RZRCheckBoxModel>();
            foreach (RZRCheckBoxModel chkBx in MyModel)
            {
                mdl.Add(chkBx);
            }

            var view = RenderRazorViewToString(ControllerContext, "_RZRChkBoxJqueryList", mdl);
            return Json(new { view });
        }

VIEW

This view should display the results of the JQuery Ajax call to the Controller action but it does not

@model IEnumerable<TestProjects.Models.RazorControls.RZRCheckBoxModel>

<h6>JQuery Result</h6>
<table class="table thead-light table-striped table-hover table-sm">
    <tr>
        <th>@Html.LabelFor(m => m.FirstOrDefault().Id)</th>
        <th>@Html.LabelFor(m => m.FirstOrDefault().Name)</th>
        <th>@Html.LabelFor(m => m.FirstOrDefault().IsChecked)</th>
    </tr>
    @foreach (var itm in Model)
    {
        <tr>
            <td>@Html.DisplayFor(m => itm.Id)</td>
            <td>
                @itm.Name
            </td>
            <td>
                @itm.IsChecked
            </td>

        </tr>
    }
</table>

I get no error message

The Jquery gets to the ajax call exits the function and returns to the View just as though it did everything it was supposed to

I'm expecting it to display the results of the Checkbox as an IEnumeration of Model (RZRCheckBoxModel) but it does not

Any help is greatly appreciated!

Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire