inserting data into select2 with asp net

Viewed 139

I need to get the id and name in the database and link this data in a select2 using ajax in asp net project, can someone help me?

1 Answers

I need to get the id and name in the database and link this data in a select2

Select2model must with id and text two properties, otherwise, it can't be recognized.

Here is a working demo you could follow:

Model:

public class TestModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

View(Index.cshtml):

<select id="SelectItem" class="form-control sel-pessoa-fisica-parentesco-parentesco-tipo" style="position: fixed !important;"></select>
    
@section Scripts
{
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script>
        $(function () {
            $("#SelectItem").select2({
                ajax: {
                    url: '/Home/GetSelect2',
                    data: function (params) {
                        return {
                            q: params.term// search term
                        };
                    },
                    processResults: function (data) {
                        console.log(data);
                        return {
                            results: data.items
                        }
                    },
                }
            });
        });
    </script>
}

Controller:

public class HomeController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }
    [HttpGet]
    public IActionResult GetSelect2(string q)
    {
        //for easy testing, i just hard coded
        //you can get data from database
        List<TestModelInAspDotnet> model = new List<TestModelInAspDotnet>();
        model.Add(new TestModelInAspDotnet() { Id = 1, Name = "aa" });
        model.Add(new TestModelInAspDotnet() { Id = 2, Name = "ac" });
        model.Add(new TestModelInAspDotnet() { Id = 3, Name = "ab" });
        model.Add(new TestModelInAspDotnet() { Id = 4, Name = "bc" });
        model.Add(new TestModelInAspDotnet() { Id = 5, Name = "bd" });
        model.Add(new TestModelInAspDotnet() { Id = 6, Name = "dc" });
        if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
        {
            model = model.Where(x => x.Name.ToLower().StartsWith(q.ToLower())).ToList();
        }
        //select2 only recognize Id and Text property
        var list = new List<object>();
        foreach (var item in model)
        {
            list.Add(new { Id = item.Id, Text = item.Name });
        }
        return Json(new { items = list });
    }
}
Related