0

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 Answer 1

0

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()

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.