Search code examples
c#jqueryasp.net-corerazorjquery-select2

Select2: Set Default value for list of dropdown items, data obtained from C# Model in razor syntax


I have a select2 drop down and I want to select default values for the list items. It works fine when I use hard code values for setting the default values of the dropdown like this $('#PlatFormTitle').val(['1','2','3']);

But I want to select values based on the data obtained from the model. Here is the code I am trying can someone please identify what am I doing wrong here.

    var PlateForms = [];

    var x;
    @foreach(var PlateForm in Model.UserPlateFormList)
    {
        @:x = '@PlateForm';
        @:PlateForms.push(x);
    } 
    $('#PlatFormTitle').val(PlateForms);
    $('#PlatFormTitle').trigger('change');

I tried this as well.

$('#PlatFormTitle').val(JSON.stringify(PlateForms));
$('#PlatFormTitle').trigger('change');

Solution

  • I test with your code,and it can work,here is the demo:

    Model:

    public class Model1 {
            public List<int> UserPlateFormList { get; set; }
        }
    

    Controller:

    public IActionResult Index()
            {
                Model1 m = new Model1 { UserPlateFormList = new List<int> { 1, 2, 3 } };
                return View(m);
            }
    

    View:

    <select id="PlatFormTitle" class="js-example-basic-multiple" multiple="multiple" style="width:200px">
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
        <option value='4'>4</option>
        <option value='5'>5</option>
        <option value='6'>6</option>
    </select>
    

    js:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" />
     <script>
            $(function () {
                $('.js-example-basic-multiple').select2();
                var PlateForms = [];
                var x;
                @foreach (var PlateForm in Model.UserPlateFormList)
                {
                    @:x = '@PlateForm';
                    @:PlateForms.push(x);
                }
                    $('#PlatFormTitle').val(PlateForms);
                    $('#PlatFormTitle').trigger('change');
            });
    </script>
    

    result:

    enter image description here