在ASP.NET MVC中使用Bootstrap双列表框

时间:2015-04-27 12:14:32

标签: asp.net asp.net-mvc twitter-bootstrap listbox

我在项目中添加了Bootstrap dual listbox plugin并且工作正常,但是如何将所选列表框的内容传递给我的控制器?它已经在一个表单中但是如果我尝试通过FormCollection它返回null。

查看:

<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 个答案:

答案 0 :(得分:2)

嗯,你可以这样做:

我假设您的form iddemoform,以下是post操作方法的样子:

[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.
       ......
       ......
}

答案 1 :(得分:0)

以下是您问题的示例。也许这将有助于未来的人们。 诀窍在于JS。

我们假设您希望将Bootstrap Dual Listbox与ASP.NET MVC 4和Kendo框架结合使用。

我们将使用Razor语法和C#。

首先,我们在视图中写入代码的占位符。我们将链接一个剑道控件和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>

然后,我们创建C#帮助程序代码。

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

然后我们创建JS代码以在运行时操作HTML并将选定的值绑定到MVC模型。

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

    }
}