Dynamically generate api url parameters in jquery url action to populate dropdown list

627 views Asked by At

I have a View in my VS project that has three dropdown lists, 2 of which are cascading and need to populate on the parent control's change. The workflow I have works great for static url calls, but I need to dynamically add the data and I am not having any luck. Below is a working static section of code and one of my many iterations of an attempt to make it work dynamically.

If needed, the example data hierarchy I have below is in descending order:Item (e.g. Food), Type (e.g. Fruit), Name (e.g. Banana)

Appreciate any input.

Working Static Code:

    function dynamicTypeList() {
       $.ajax({
           url: '@Url.Action("", "api/types/1")',

           success: function (data) {
               $("#Type_Id").empty();
               $("#Name_Id").empty();
               $("#Type_Id").append("<option value>Select Type (NEW)</option>");
               $("#Name_Id").append("<option value>Select Name (NEW)</option>");
               for (var i in data) {
                   $("#Type_Id").append("<option value='" + (i + 1) + "'>" + $(data)[i] + "</option>");
               }
           }
       });
   };

Broken Dynamic Code:

    function dynamicTypeList() {
       selItem = $("#Item_Number").val();
       console.log(selItem);
       $.ajax({
           url: '@Url.Action("", "api/types/" + selItem)',

           success: function (data) {
               $("#Type_Id").empty();
               $("#Name_Id").empty();
               $("#Type_Id").append("<option value>Select Type (NEW)</option>");
               $("#Name_Id").append("<option value>Select Name (NEW)</option>");
               for (var i in data) {
                   $("#Type_Id").append("<option value='" + (i + 1) + "'>" + $(data)[i] + "</option>");
               }
           }
       });
   };
1

There are 1 answers

1
Brian Mains On BEST ANSWER

Assuming "api" is the controller and "types" is the action, try replacing the url variable with:

url: '@Url.Action("types", "api")' + sellItem,

sellItem is a JavaScript variable and needs to stay completely on the client. Or you can use this technique so you can use the natural URL parameter passing within Url.Action:

How to access javascript variable within @URL.Action()