-1

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 ?

R15
  • 13,982
  • 14
  • 97
  • 173
  • You will make use `ajax` call to bind data when the user clicks on the dropdown. [This](https://stackoverflow.com/questions/30084568/populate-dropdownlist-using-ajax-mvc-4) should give you a good starting point – Izzy Dec 13 '22 at 09:52
  • @Izzy - There I am able to Change event which gets fired when we select something from ddl. I need event name when we click on ddl. – R15 Dec 16 '22 at 16:20

2 Answers2

1

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.

ChadT
  • 7,598
  • 2
  • 40
  • 57
0

I was able to bind data to dropdown when I click on it.

<div>
  @Html.DropDownList("DesignDropdown", new List<SelectListItem> { new SelectListItem { Text = "--Select--", Value = "" } })
</div>

Below is JavaScript code in the same page inside <script> tag

var url = '@Url.Action("GetDesign", "Design")'; // url/api to get data
var ddl = $('#DesignDropdown'); //get ddl instance
$('#DesignDropdown').focus(function () {

    $.post(url, {id: designId}, function (response) {
        ddl.empty(); //clear if already data there
        ddl.append($('<option></option>').text("--Select--").val("")); //first item as --Select--
        $.each(response, function (index, item) {
            ddl.append($('<option></option>').text(item.Name).val(item.DesignId)); //bind api result to ddl
        });
    });

    $('#DesignDropdown').blur();
})
R15
  • 13,982
  • 14
  • 97
  • 173