Populate selected values into model

4 posts, 1 answers
  1. David
    David avatar
    3 posts
    Member since:
    Aug 2017

    Posted 14 Nov Link to this post

    Hi there, Im using MVC 5 and really battling to populate the model with what is currently in the listbox. I have done some research and can see recommendations to use Ajax but surely this should be a basic model binding?

    I can pass the selected items correctly back to the controller via the event on add however Im still lost how I can assign this to the DeviceList object within the model. Am I being silly? Many thanks :)

    See Model :

        public class DeviceGroupDetailModel
        {
            public int Id { get; set; }
            [Display(Name = "Name")]
            public string Name { get; set; }
            public string Company { get; set; }
            public List<DeviceModelList> DeviceList { get; set; }


            public DeviceGroupDetailModel()
            {
                DeviceList = new List<DeviceModelList>();
            }
        }

    See Razor :

    (In Create.cshtml)

    @using (Html.BeginForm("Create", "DeviceGroups", new { area = "" }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        <div class="wrapper wrapper-content animated fadeInRight">
            <div class="row">
                <div class="col-lg-12">
                    <div class="ibox float-e-margins">
                        <div class="ibox-title">
                            <h5>New group details</h5>
                        </div>
                        <div class="ibox-content">
                            @Html.Partial("_DeviceGroupDetail", Model)
                            @Html.Partial("_DeviceList", Model)
                            <div class="form-group">
                                <div class="col-sm-10">
                                    <button class="btn btn-primary" type="submit">Create group</button>
                                    &nbsp;|&nbsp;
                                    @Html.ActionLink("Cancel", "Index", "DeviceGroups", new { area = "" }, null)
                                </div>
                            </div>
                            <div class="clearfix"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        <script type="text/javascript">
            var dataSource;
            $(document).ready(function () {
                dataSource = new kendo.data.DataSource({
                    serverFiltering: false,
                    transport: {
                        read: {
                            url: '@Url.Action("DeviceList_Read", "DeviceGroups")',
                        dataType: "json"
                    }
                },
                requestStart: function () {
                    kendo.ui.progress($("#alldevicesid"), true);
                    kendo.ui.progress($("#selectedid"), true);
                },
                requestEnd: function () {
                    kendo.ui.progress($("#alldevicesid"), false);
                    kendo.ui.progress($("#selectedid"), false);
                },
                batch: false
            });

            dataSource.fetch(function () {
                var data = this.data();
                var alldevices = $("#alldevices").data("kendoListBox");
                var selected = $("#selected").data("kendoListBox");
                for (var i = 0; i < data.length; i++) {
                    alldevices.add(data[i]);
                    selected.add(data[i]);
                }
            });
        });

            function onSelectListBoxAdd (e) {
                //debugger
                $.ajax({
                    type: "POST",
                    url: "/DeviceGroups/SelectedDevices",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ selectedItems: $('#selected').data('kendoListBox').dataItems() }),
                    dataType: "json",
                    success: function (result) {
                        alert("Successfully sent to server: " + result.map(function (x) {
                            return x.SerialNumber
                        }))
                    }
                });
        }
        </script>
    }

    (In DeviceList partial view)

    <div id="alldevicesid" class="col-sm-3">
                            <label for="alldevices" id="all">All Devices</label>
                            @(Html.Kendo().ListBox()
                                .Name("alldevices")
                                .Toolbar(toolbar =>
                                {
                                    toolbar.Position(Kendo.Mvc.UI.Fluent.ListBoxToolbarPosition.Right);
                                    toolbar.Tools(tools => tools
                                        .TransferTo()
                                        .TransferFrom()
                                        .TransferAllTo()
                                        .TransferAllFrom()
                                    );
                                })
                                .DataValueField("DeviceId")
                                .DataTextField("SerialNumber")
                                .Draggable(true)
                                .DropSources("selected")
                                .ConnectWith("selected")
                                .BindTo(new List<DeviceModelList>())
                                .Selectable(ListBoxSelectable.Multiple)
                            )
                        </div>

                        <div id="selectedid" class="col-sm-3">
                            <label for="selected">Selected Devices</label>
                            @(Html.Kendo().ListBox()
                                    .Name("selected")
                                    .Draggable(true)
                                    .DropSources("alldevices")
                                    .DataValueField("DeviceId")
                                    .DataTextField("SerialNumber")
                                    .ConnectWith("alldevices")
                                    .BindTo(new List<DeviceModelList>())
                                    //.BindTo(Model.DeviceList)
                                    .Selectable(ListBoxSelectable.Multiple)
                                    .Events(events => events
                                    .Add("onSelectListBoxAdd"))
                            )
                        </div>

     

    In Controller:

            public ActionResult SelectedDevices(List<DeviceModelList> selectedItems)
            {
                return Json(selectedItems);
            }

            private IEnumerable<DeviceModelList> GetDeviceList()
            {
                List<Device> devices = Managers.DeviceManager.GetList(DevicePart.VCM001, PaginationOptions.NoPaging()).Take(10).ToList();
                return Mapper.Map<IEnumerable<DeviceModelList>>(devices);
            }

            public ActionResult Create()
            {
                return View(new DeviceGroupDetailModel());
            }

            [HttpPost]
            public async Task<ActionResult> Create(DeviceGroupDetailModel model)
            {

            }

  2. David
    David avatar
    3 posts
    Member since:
    Aug 2017

    Posted 15 Nov Link to this post

    Any update?
  3. Answer
    Stefan
    Admin
    Stefan avatar
    1394 posts

    Posted 16 Nov Link to this post

    Hello, David,

    In this scenario, the values have to be manually added to a model object.

    The string that contains the selected items has to be destructured on the Controller and then the data to be used to make a new model object.

    The ListBox was not intended for update Actions, and it will not automatically format its selected value in order to match the model.

    One of my colleagues made a runnable example for this, but based on the provided code I can assume that this post was already read:

    https://www.telerik.com/forums/passing-data-to-controller-for-%27selected%27-listbox

    ======================================

    As for the updates, please have in mind that the forums do not have a set ETA as the support tickets, but still, we are trying to provide a response within 2 business days(48 hours).

    Let me know if you need additional assistance on this matter.

    Regards,
    Stefan
    Progress Telerik
    Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
  4. David
    David avatar
    3 posts
    Member since:
    Aug 2017

    Posted 17 Nov in reply to Stefan Link to this post

    Thanks, just in case anyone needs the info :

            function onFormSubmit()
            {
                var dataObject = JSON.stringify({
                    'Name': document.getElementById('Name').value,
                    'DeviceList': $('#selected').data('kendoListBox').dataItems()
                });

                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Create", "DeviceGroups")',
                    contentType: "application/json; charset=utf-8",
                    data: dataObject,
                    dataType: "json",
                    success: function (result) {
                        window.location.href = result;
                    },
                    error: function () { alert('An error occured during the creation of the group'); }
                });

                return false;
            }

     

            [HttpPost]
            public async Task<ActionResult> Create(DeviceGroupDetailModel model)
            {

                    return Json(Url.Action("Index"));

            }

Back to Top