0

I'm trying to use Select2 in Razor in ASP.NET MVC. But I can't get work.

  $(document).ready(function () {
            $(".genreOptions").select2({
                tags: true,
                ajax: {
                    url: 'http://localhost:65148/NewProfile/Genres',
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            q: params.term, // search term
                            page: params.page
                        };
                    },
                    processResults: function (data, page) {
                        var newData = [];
                        $.each(data, function (index, item) {
                            newData.push({
                                id: item.Id,  //id part present in data 
                                text: item.Genre  //string to be displayed
                            });
                        });
                        return { results: newData };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 1
            });

@Html.DropDownListFor(x => x.BandProfile.Genres, Enumerable.Empty<SelectListItem>(), new { @class="genreOptions", multiple = "multiple", style ="width: 100%;"} )

The searching for tags works fine. But when I post the form, the count of the input field Is 0. How can I capture the data from the input form?

1 Answer 1

1

@Bryan I build up a javascript array and pass it with ajax to the server. Seems to work ok for my purposes. Perhaps you could try that. The selectors I put below will be different than what you need but here is the general idea...

On Click

$('#submitButton').click(function () {

      fillHiddenInput();

      var dataToSend = $('#hiddenInput').val();

      //Submit the form with ajax or however you want to get dataToSend to server
});

FillHiddenInput function...

var fillHiddenInput = function () {

      $('#hiddenInput').val("");
      var stuff = [];

      $('.ms-selection .ms-list li ul').children('li').each(function (){

          if ($(this).hasClass('ms-selected')) 
           {
              stuff.push($(this).children('span').text());
           }

      });

    $('#hiddenInput').val(stuff);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't want to do that. I want to use razor here.

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.