Setting default values for Select2 input with tagging in ASP.NET MVC is a simple process that can greatly enhance the user experience

I am currently utilizing a Select2 input box as a tag controller in my view:

CSHTML

<input id="tagSelector" type="hidden" style="width: 300px"/>

JS

  $('#tagSelector').select2({
            placeholder: 'Select a tag...',
            multiple: true,
            ajax: {
                url: '@Url.Action("SearchTags", "UnitDetails")',
                dataType: 'json',
                data: function(term, page) {
                    return {
                        searchTerm: term
                    };
                },
                results: function(data, page) {
                    return { results: data };
                }
            },
            createSearchChoice: function(term) {
                return { id: term, text: term };
            }
        }).on("removed", function(e) {
            var url = '@Url.Content("~/UnitDetails/UnTagUnit/" + Model.ViewUnitContract.Id)';
            var id = e.val;
            var tagName = e.choice.text;
            console.log(id + " : " + tagName);

            $.ajax({
                url: url,
                data: { selectedItem: tagName },
                type: 'GET',
                dataType: 'json',
                success: function() {
                },
                error: function() {
                }
            });
        })
            .on("select2-selecting", function(e) {
                var url = '@Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
                var id = e.val;
                var tagName = e.object.text;
                console.log(id + " : " + tagName);

                $.ajax({
                    url: url,
                    data: { selectedItem: tagName },
                    type: 'GET',
                    dataType: 'json',
                    success: function() {
                    },
                    error: function() {
                    }
                });
            });
    });

C#

public JsonResult GetInitialTags(int id)
{
    Model = new UnitDetailsModel(UnitClient.GetUnit(id));
    foreach (var tag in Model.ViewUnitContract.Tags)
    {
        Model.TagsSelected.Add(tag);
    }

    var result = Model.TagsSelected.Select(a => new
        {
            id = a.Id,
            text = a.Name
        });

    return Json(result, JsonRequestBehavior.AllowGet);
}

I am currently struggling with implementing the initSelection method to pre-fill the input box with already selected tags. Any guidance on this matter would be greatly appreciated, as I am finding it quite challenging at the moment :)

Answer №1

After much experimentation, I managed to solve the issue by incorporating the initSelection property into my JavaScript code:

...
            initSelection: function (element, callback) {
                $.get('@Url.Action("GetInitialTags", "UnitDetails", new { id = Model.ViewUnitContract.Id })', function (initTags) {
                    var tags = [];

                    for (var i = 0; i < initTags.length; i++) {
                        tags.push({ "id": initTags[i].id, "text": initTags[i].text });
                    }

                    callback(tags);
                });
            },
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...

Support for Vue 3.4 same-name shorthand has been added to VS Code

After upgrading my Vue 3 project to version 3.4, I encountered an issue with vs-code highlighting same-name shorthand as an error, even though it was functioning correctly in my code. I am using the volar extension. Is there a way to resolve this so that v ...

Enhancing the appearance of list options in Autocomplete Material UI by utilizing the renderOption feature

I'm putting in a lot of effort to customize the option elements in the autocomplete list. My plan is to achieve this using the renderOptions prop, where I can create DOM elements and easily apply styles with sx or styled components. However, somethin ...

A guide on updating the SQL order value through a select option using PHP and jQuery

To modify the arrangement of SQL data according to the chosen select option, I am looking to adjust the ORDER value. Within my action.php file, I retrieve values from the database and aim to incorporate a sorting select option that allows for changing the ...

Error Encountered: Custom Validation Method Not Defined

I encountered a runtime error stating that 'cvLeapYear_ServerValidate' is undefined The validator is set up as follows <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="cvLeapYear_ServerVali ...

Is there a specific API within the framework for detecting reentrancy?

I am searching for a way to prevent reentrancy for a large number of methods. For individual methods, the following code can be used: bool _isInMyMethod; void MyMethod() { if (_isInMethod) throw new ReentrancyException(); _isInMethod = t ...

Establishing a variable to serve as a function invocation

Is there a way I can assign a variable to either .prev() or .next()? Here is an example of what I am trying to do: if(x == y) var shift = '.prev()'; else var shift = '.next()'; $("li.active").removeClass('a ...

Customize Button Colors in Bootstrap 4

I'm encountering difficulties when attempting to change the color of the buttons labeled "Print," "Excel," and "PDF". Despite referring to a guide, I wasn't able to succeed. The provided test case differs from my code but shares the same CSS and ...

Creating an identifier for the jQuery slideToggle function involves assigning a unique class or ID to

I am currently working on creating an identifier for the jQuery slide.Toggle function. In my PHP code, I have a loop that prints values, each with a button and a div that should be able to slide toggle. So far in PHP, here is what I have attempted, withou ...

Adjust the appearance using Timeout within a React component

I am facing a challenge with updating the style in React - specifically, the opacity of a Div element is not updating despite successfully updating the opacity in a timeout event. import React from 'react'; function PortItem(props){ let style ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

jQuery getJSON is returning an empty output

I have been attempting to integrate JSON data into my HTML file using jQuery. However, I am not getting any output in my HTML page, not even null or undefined When I tried using external JSON data from Flickr, all I could see was [Object] Even when test ...

Check if the div has been clicked, even if its child elements have also

Is it possible to check if both a div and its child are clicked using jQuery? $('div').click(function(e){ if(e.target.id == 'test') alert(e.target.id); }); I have a specific div with an id of #test in my HTML code, and wh ...

Struggling to send the correct cookies to the API server using Next.js

I have set up an API express server on api.mydomain.com and a Next.js website on mydomain.com. My Next.js application uses getServerSideProps to request data from the API for displaying on the page. However, I am facing an issue where I can set cookies for ...

Is it possible for issues to arise when serving a web app using the "Globals" module in the Mean Stack?

Looking to transfer a variable (a constructed filename) from one file to another within an API can be quite challenging. One solution that comes to mind is utilizing globals, but with my current code structure, it seems like the only viable option. To addr ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Don't forget to set up your reminder notifications for Apple iOS devices with simple php

Here are the four notification settings available: 1. Renew Tax 2. Renew Health Insurance 3. Renew Car Insurance 4. Renew Residential Insurance If a user decides to turn off any of these settings on their mobile phone, NO notifications will be sent. How ...

Clicking on a button in the Shield UI Grid Toolbar will apply filters to

Currently, I am working with a grid that utilizes a template for the toolbar. In this grid, there is a column labeled "Status." My goal is to filter the rows so that only those where the Status equals Request to Reschedule, Cancelled, Office Call Required, ...

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...