This is a migrated thread and some comments may be shown as answers.

Passing data to controller for 'selected' listbox

6 Answers 2153 Views
ListBox
This is a migrated thread and some comments may be shown as answers.
Jennifer
Top achievements
Rank 1
Jennifer asked on 23 Aug 2017, 05:03 PM

Hello,

I'm working on a project where I'm trying to use the Listbox. My end goal is to have the items in the 'selected' listbox passed to a POST controller.

Controller.cs

01.[HttpGet]
02. public ActionResult Create()
03. {
04.     List<SelectListItem> memberList = MemberRepository.ListAllMembers(request);
05.     ViewBag.memberList = memberList;
06. 
07.     return View("Create", new MemberSelection());
08. }
09. [HttpPost]
10. [ValidateAntiForgeryToken]
11. public ActionResult Create(MemberSelection m)
12. {
13.     if (ModelState.IsValid)
14.             MemberRepository.Create(request);
15.         else
16.             return View("Create",m);
17.     return RedirectToAction("Members");
18. }

 

Create.cshtml

001.@model MembersDomain.Entities.Member
002. 
003.@{
004.    ViewBag.Title = "Create";
005.    Layout = "~/Views/Shared/_Layout.cshtml";
006.}
007. 
008.@if (!Html.ViewData.ModelState.IsValid)
009.{
010.    <div class="alert alert-danger" id="validationSummary">
011.        @Html.ValidationSummary()
012.    </div>
013.}
014.<div class="row" style="margin-top: 25px;">
015.    <div class="col-lg-12">
016.        <h4>Select Members</h4>
017.    </div>
018.</div>
019.<div class="row" style="margin-top: 25px;">
020.    <div class="col-lg-12">
021.        <p>Use this form to add members to a group.</p>
022.    </div>
023.</div>
024.@using (Html.BeginForm("Create", "Members", FormMethod.Post, new { id = "create" }))
025.{
026.    @Html.AntiForgeryToken()
027.    @Html.ValidationSummary()
028. 
029.    <div class="row" style="margin-top: 25px;">
030.        <div class="col-lg-12">
031.            <strong>Selected Members:</strong>
032.        </div>
033.    </div>
034.    <div class="row" style="margin-top: 25px;">
035.        <div class="col-lg-12">
036.            <div id="example" role="application">
037.                <div class="demo-section k-content wide">
038.                    <label for="optional" id="allMembers">All Members</label>
039.                    <label for="selected">Selected</label>
040.                    <br />
041.                    @(Html.Kendo().ListBox()
042.            .Name("optional")
043.            .Toolbar(toolbar =>
044.            {
045.                toolbar.Position(Kendo.Mvc.UI.Fluent.ListBoxToolbarPosition.Right);
046.                toolbar.Tools(tools => tools
047.                    .TransferTo()
048.                    .TransferFrom()
049.                    .TransferAllTo()
050.                    .TransferAllFrom()
051.                );
052.            })
053.            .HtmlAttributes(new { title = "AllMembers" })
054.            .ConnectWith("selected")
055.            .BindTo(ViewBag.memberList)
056.                    )
057. 
058.                    @(Html.Kendo().ListBox()
059.            .Name("selected")
060.            .HtmlAttributes(new { title = "SelectedMembers" })
061.            .BindTo(new List<SelectListItem>())
062.            .Selectable(ListBoxSelectable.Multiple)
063.                    )
064.                </div>
065.            </div>
066.        </div>
067.    </div>
068.    <div class="row" style="margin-top: 25px;">
069.        <div class="col-lg-12">
070.            <p><a class="btn btn-primary btn-lg" href="#" onclick="document.getElementById('create').submit()">Submit</a></p>
071.        </div>
072.    </div>
073.}
074. 
075.<style>
076.    .demo-section label {
077.        margin-bottom: 5px;
078.        font-weight: bold;
079.        display: inline-block;
080.    }
081. 
082.    #allMembers {
083.        width: 270px;
084.    }
085. 
086.    #example .demo-section {
087.        max-width: none;
088.        width: 515px;
089.    }
090. 
091.    #example .k-listbox {
092.        width: 236px;
093.        height: 310px;
094.    }
095. 
096.        #example .k-listbox:first-of-type {
097.            width: 270px;
098.            margin-right: 1px;
099.        }
100.</style>
101. 
102.<script type="text/javascript">
103.    function sendAntiForgery() {
104.        return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }
105.    }
106.</script>

 

I am using Visual Studio 2015 and the project is ASP.NET MVC. Any insight is appreciated!

6 Answers, 1 is accepted

Sort by
0
Georgi
Telerik team
answered on 25 Aug 2017, 12:43 PM
Hi Jennifer,


Possible solution is to get all items inside the selected list box with the dataItems  method and append them to the body of the request to the server.

e.g.

$('#submit-form').on('click', function () {
         $.ajax({
             type: "POST",
             url: "/Home/Create",
             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.Text
                 }))
             }
         });
     })


I have assembled small sample (send-items-from-listbox.zip) which illustrates the aforementioned approach.


Regards,
Georgi
Progress Telerik
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Robert Michels
Top achievements
Rank 1
answered on 02 Oct 2017, 07:30 PM

Hi Georgi,

We are having a similar issue posting the selected items from a listbox back to a controller. We understand your suggestion in principle and the code sample in the thread seems to make sense.

However the sample code zip you attached is for a kendo grid component, not for a listbox. Is there a sample project for the listbox available? It would help us expedite this implementation.

 

[quote]Georgi said: 

I have assembled small sample (send-items-from-listbox.zip) which illustrates the aforementioned approach.

[/quote]

 

Thanks,

John

0
Georgi
Telerik team
answered on 04 Oct 2017, 12:34 PM
Hello Robert,

I apologize for the inconvenience, indeed I have sent the wrong project.

Attached you will find the proper project.


Regards,
Georgi
Progress Telerik
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Krishna
Top achievements
Rank 1
answered on 08 Nov 2017, 05:24 AM

Hello Georgi,

Thanks for your solution. I am also having the same problem in one of my project but, with me, i have more than one Listboxes and i do not have any button which can trigger the action. Please find the detailed scenario...

I have 2 Kendo tabs (tab1, tab2) and each tabs have some multiple listboxes. Now, once i select a list from the list box and go to the next tab, i need the selected data to be passed to my controller as my tab2 listbox contents are dependant on tab1 listbox selections.

Is there any other approach that is suitable for this scenario?

Thanks,

Krishna

 

0
Georgi
Telerik team
answered on 10 Nov 2017, 08:01 AM
Hi Krishna,

A possible solution is to check whether the user is opening the second tab within the select event handler and if he does send the selected items from the first tab to the server.

I have modified the sample to apply the above solution, please examine it and let me know if it helps you.


Regards,
Georgi
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.
0
TJim
Top achievements
Rank 1
answered on 19 Jul 2019, 06:13 PM

 

For future posters, this is what worked for me in asp.net core

function onRemove(e) {
$.ajax({
    type: "POST",
    url: "/OrgStructure/RemoveCaps",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(e.dataItems),
     dataType: "json"
     //success: function (result) {
     // alert("Successfully sent to server: " + result.map(function (x) {
     //        return x.Text
     //    }))
     //}
 });
Tags
ListBox
Asked by
Jennifer
Top achievements
Rank 1
Answers by
Georgi
Telerik team
Robert Michels
Top achievements
Rank 1
Krishna
Top achievements
Rank 1
TJim
Top achievements
Rank 1
Share this question
or