2

I added the Bootstrap dual listbox plugin on my project and it's working fine, but how can I pass the contents of the selected listbox to my controller? It's already inside a form but if I try to get it through FormCollection it returns as null.

View:

<div class="form-group col-md-7" style="margin-left: -15px;">
    <select style="display: none;" multiple="multiple" size="10" name="dualListbox" id="dualListbox" class="demo2">
        @if (ViewData["Customers"] != null)
        {
            foreach (var item in ViewData["Customers"] as List<Testbox.Models.Customer>)
            {
                <option value="customer">@item.NAME @item.LName - @item.PHONE11</option>
            }
        }
    </select>
</div>

2 Answers 2

3

Well you can do it as below:

I'll assume that your form id is demoform and below is how the post action method will look like:

[HttpPost]
public ActionResult GetForm()
{
       string values = Request.Form["dualListbox"];
       //Form[key] will be 'name' property of your select box

       //You will get values as comma ',' separated values like option 1,
       //option 2, option 4 etc., and I hope you know how you can get each 
       //options by splitting the comma separated values.
       ......
       ......
}
Sign up to request clarification or add additional context in comments.

6 Comments

For some reason this also returns as null. I might be doing something wrong, but from what I've seen this plugin takes a Listbox and splits it in two. Say, if my original one was named "myList", it creates two lists named "myList_helper1" and "myList_helper2". I tried writing string values = Request.Form["dualListbox_helper1"]; but it still comes up as null.
I created a VS project for this and followed the same step as mentioned in docs!! and it worked for me!! I think either the problem might be because of adding options dynamically or the value you are adding to each of your option is same where as its different in demo!! so try adding a dynamic values to your option!! Hope you got it @NikolMarg
Unfortunately it doesn't work when I use this plugin. When I remove the script and keep it as a simple <select> element it works, but when I turn it to a dual listbox with the plugin it doesn't.
No Nikol!! Just try what I said!! Give unique option value like <option value="customer1">....</option> <option value="customer2">..</option> Like that...
I tried that already and that's not the problem. The only way it seems to work is when I don't use the plugin at all and I want to keep using it if possible. I tried to give all options different values dynamically and I also tried to put all options manually instead of doing it by code. Still nothing.
|
0

Here is an example to your question. Maybe this will help people in the future. The trick is in the JS.

Let's say you want to use Bootstrap Dual Listbox in conjuction with ASP.NET MVC 4 and Kendo framework.

We will use the Razor syntax and C#.

First, we write in the view the placeholder for the code. We will be linking a kendo control and the Bootstrap Dual Listbox

<script>
    var urlGetCascadeMultiSelectBrandTypeByBrand = "@(Url.Action("GetCascadeMultiSelectBrandTypeByBrand", "DropDownList"))";
</script>

<div class="col-md-12 col-sm-12 col-xs-12 padding-0 ">
    <div class="col-md-6 col-sm-6 col-xs-12">
        @Html.LabelFor(m => m.BrandId)<br />
        @(Html.Kendo().DropDownListFor(m => m.BrandId)
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetCascadeDdlBrandBySegment", "DropDownList")
                .Data("filterSegments");
        })
        .ServerFiltering(true);
    })
    .DataTextField("BrandName")
    .DataValueField("BrandId")
    .Filter(FilterType.Contains)
    .CascadeFrom("SegmentId")
    .OptionLabel("Select brand")
    .Events(evt => evt.Change("onBrandIdDdlChange"))
    .HtmlAttributes(new { @style = "width: 100%;" }))
        @Html.ValidationMessageFor(m => m.BrandId)
    </div>
    <div class="col-md-6 col-sm-6 col-xs-12">
        &nbsp;
    </div>
</div>

<div class="clear height10"></div>

<div class="col-md-12 col-sm-12 col-xs-12 padding-0 ">
    <div class="col-md-12 col-sm-12 col-xs-12">

        @Html.LabelFor(m => m.BrandTypeIdList)<br />
        @if (Model.IsEdit)
        {
            @Html.ListBoxFor(m => m.BrandTypeIdList, Html.GetBrandTypeByBrandIdSelectListItemsList(Model.BrandId))

        }
        else
        {
            @Html.ListBoxFor(m => m.BrandTypeIdList, new List<SelectListItem>())
        }

        @Html.ValidationMessageFor(m => m.BrandTypeIdList)
    </div>
</div>

Then, we create the C# helper code to go with it.

public static IEnumerable<SelectListItem> GetBrandTypeByBrandIdSelectListItemsList(this HtmlHelper htmlHelper, int brandId)
{
    using (var dbContext = new Entities())
    {
        return dbContext.BrandType.Where(x => x.Active == true && x.BrandId == brandId).Select(BrandTypeToDdlSelector).ToList();
    }
}

public static Func<BrandType, SelectListItem> BrandTypeToDdlSelector
{
    get
    {
        return (x => new SelectListItem()
        {
            Value = x.BrandTypeId.ToString(),
            Text = x.Name
        });
    }
}

public JsonResult GetCascadeMultiSelectBrandTypeByBrand(int? brandId)
{
    var brandTypesList = DbContext.BrandType.Where(p => p.Active == true);

    if (brandId != null)
    {
        brandTypesList = brandTypesList.Where(p => p.BrandId == brandId);
    }

    return Json(brandTypesList.Select(x => new { BrandTypeId = x.BrandTypeId, BrandTypeName = x.Name }), JsonRequestBehavior.AllowGet);
}

Then we create the JS code to manipulate the HTML at runtime and bind the selected values to the MVC model.

var brandTypeIdDualListbox = new Object();

$(document).ready(function ()
{   
    //we create the dual list control
    brandTypeIdDualListbox = $('select[name="BrandTypeIdList"]').bootstrapDualListbox({
    nonSelectedListLabel: 'Non-selected',
    selectedListLabel: 'Selected',
    preserveSelectionOnMove: 'moved',
    moveOnSelect: false,    
    });

    //we setup the change event for the control
    $('select[name="BrandTypeIdList').on('change', function (args)
    {
        //we traverse every option
        $("#BrandTypeIdList option").each(function (index,element)
        {
            //we check if the element has the `data-sortindex` attribute
            if (!!$(element).attr('data-sortindex'))
                $(element).attr('selected', 'selected');
            else
                $(element).removeAttr('selected');
        });
    })
});


function filterBrands()
{
    var brandId = $("#BrandId").val();
    if (brandId == "")
        brandId = "-1";
    return {
        BrandId: brandId
    };
}

function populateBrandTypeIdDualListbox()
{
    $.getJSON(urlGetCascadeMultiSelectBrandTypeByBrand, filterBrands(), function (data)
    {
        var items;
        $.each(data, function (i, item)
        {
            brandTypeIdDualListbox.append("<option value=" + item.BrandTypeId/*Value*/ + ">" + item.BrandTypeName/*Key or Text*/ + "</option>");
        });
        brandTypeIdDualListbox.trigger('bootstrapDualListbox.refresh', true); // we refresh the control
    });
}

function onBrandIdDdlChange(evt)
{
    var brandIdDropDownList = $("#BrandId").data("kendoDropDownList");

    $('#BrandTypeIdList').empty();
    brandTypeIdDualListbox.trigger('bootstrapDualListbox.refresh', true);
    if ($("#BrandId").val() == "" || $("#BrandId").val() == "-1")
    {
        //if no value is selected we disable the control
        $(".bootstrap-duallistbox-container").find("*").prop("disabled", true);
    }
    else
    {
        populateBrandTypeIdDualListbox();
        $(".bootstrap-duallistbox-container").find("*").prop("disabled", false); // we enable the control

    }
}

Comments

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.