Home > Blockchain >  How to bind data to Html.DropDownList when I click on it - ASP.NET MVC
How to bind data to Html.DropDownList when I click on it - ASP.NET MVC

Time:12-20

I am using ASP.NET MVC dropdown and binding data to it. Data already I have in model which I got from API call.

@Html.DropDownList("productddl", Model.selectListItems, "--Select--")

What I need is to bind data to dropdown when I click on it. I want to make API call when user click on it and bind the data.

What event do I need to use, How can I do that ?

CodePudding user response:

ASP.NET runs in the server and it responds to HTTP requests. Altering a select list does not trigger a HTTP request, it is a purely browser based operation. You can write some JavaScript code which listens to the client side event that this raises (likely onchange), and then write your own code to perform a request to the server.

CodePudding user response:

See the following example that uses the ajax() method to bind the DropDownList data dynamically.

The Index.cshtml view:

@{
    // Defining the DropDownList id/name
    var ddlId = "productddl";
}
<script>
    window.onload = function () {

        // First step is creating the `mousedown` event listener on the document level, 
        // to perform data binding before the DropDownList click event will be raised.
        document.addEventListener('mousedown', function (e) {
            
            let ddlId = "@ddlId";
            // This condition is checked to ignore the 'click' event on the `option` items
            if (e.target.id == ddlId) {
                $.ajax({
                    type: "GET",
                    url: '@Url.Action("Refresh", "Home")',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        // Load a new data to the DropDownList
                        $(document.getElementById(ddlId)).empty();
                        var obj = document.getElementById(ddlId);
                        for (var i = 0; i < data.length; i  ) {
                            opt = document.createElement("option");
                            opt.value = data[i].Index;
                            opt.text = data[i].Text;
                            obj.appendChild(opt);
                        }
                    }
                });
            }
        }, true);
    }    
</script>

<body>
    <div>
        @Html.DropDownList(ddlId, new List<SelectListItem>(){}, "--Select--")    
    </div>
</body>

The HomeController.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
...
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    // This method is calling from the view by sending the AJAX request.
    public JsonResult Refresh()
    {
        return Json(Records(), new System.Text.Json.JsonSerializerOptions()); 
    }

    // The function below generates a random list of items are passing to the view 
    // and displaying in the DropDownList.
    // *** It should be replaced/fixed to use your API. 
    private List<DataViewModel> Records()
    {
        var rand = new Random();
        var list = new List<DataViewModel>();
        for (int i = 0; i < rand.Next(3, 20); i  )
        {
            var next = rand.Next(10, 99);
            list.Add(new DataViewModel { Text = "Title"   next, Index = next });
        }
        return list;
    }
}

The data model:

// This data model is defined only for test purpose 
public class DataViewModel
{
    public string Text { get; set; }
    public int Index { get; set; }
}

  • Related