3

I'm trying to update a second dropdown list based on the selection of the first dropdown list using Ajax. It appears to be working, I've stepped through the code and selectedId is updating with the correct Id, however the dropdown list itself is not updating. So I think I've missed something somewhere, I need to update the #modelDropDown I think in the success function but not sure how to do it.

jQuery/Ajax:

$('#manufacturerDropDown').change(function () {
    var selected = $(this).val();
    $.ajax({
        url: '/Home/Index',
        data: { id: $('#manufacturerDropDown option:selected').val() },
        type: "post",
        cache: false,
        success: function () {
        },
        error: function () {
        }
    });
});

Controller Method

public IActionResult Index(string id)
{
    Guid selectedId = Guid.Parse(id);

    var vm = new HomeViewModel
    {
        Manufacturers = context.ManufacturersTable.OrderBy(x => x.Manufacturer).ToList(),
        Models = context.ModelsTable.OrderBy(x => x.ModelName).Where(x => x.ManufacturerId == selectedId).ToList(),
    }
}

Previous question for context: Master/Detail dropdown filtering using Lambda in ASP.NET

Edit: I've gotten closer with the jQuery below, the html is loaded, I can see it in the error log but the console returns the error Uncaught TypeError: Cannot use 'in' operator to search for 'length' in <!DOCTYPE html>.

$('#manufacturerDropDown').change(function () {
    var selected = $(this).val();
    $.ajax({
        url: '/Home/Index',
        data: { id: $('#manufacturerDropDown option:selected').val() },
        type: "post",
        cache: false,
        success: function (result) {
            alert(result);
            var modelDropDown = $('#modelDropDown');
            modelDropDown.empty();
            $.each(result, function () {
                modelDropDown.append(
                    $('<option>', {
                        value: this.Value
                    }).text(this.Text)
                );
            });
        },
        error: function () {
        }
    });
});

Response from Ajax call

Cache-Control: no-cache, no-store
Content-Type: text/html; charset=utf-8
Date: Mon, 08 Jul 2019 23:28:54 GMT
Persistent-Auth: true
Pragma: no-cache
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
X-Powered-By: ASP.NET
4
  • Possible duplicate of better way to load 2 dropdown in mvc Commented Jul 8, 2019 at 22:13
  • Could you please provide a snapshot of what result(the response from the server) looks like. You get that error because you are trying to look through the response content which is not exactly a collection. I believe you are very close to your solution, and we can help you with that if you show us what the response of the ajax call looks like. Commented Jul 8, 2019 at 23:21
  • Thanks @HimanshuPant. The error log appears to return the entire html page with the above error and complains specifically about the $.each(result, function () {line. The alert that pops up with alert(result) also returns the entire html page. Commented Jul 8, 2019 at 23:34
  • @HimanshuPant I've added the response from dev tools to the question too. Commented Jul 8, 2019 at 23:38

1 Answer 1

1

Okay, Based on our conversation in the comments and my preliminary assessment. It looks like the action method is returning html instead of serialized json for the collection of object that you have. Also I don't really know what the structure of the Manufacturers and Models is, So I'm going to do an example of similar data and you can adjust it according to your classes.

//This is my ViewModel
public class Model {
    public string Value {get;set;}
    public string Text {get;set;}
    public string ManufacturerID {get;set;}
}

Change your controller to do this.

public IActionResult Index(string id)
{
    //You will have to update the structure of data according to you viemodel.
    //Also apply you logic for database lookup
    var ModelCollection = _ctx.Models.Where(mdl => mdl.ManufacturerID == id).ToList();
    return Ok(ModelCollection);
}

Then you would change your ajax call to this.

$('#manufacturerDropDown').change(function () {
    var selected = $(this).val();
    $.ajax({
        url: '/Home/Index',
        data: { id: $('#manufacturerDropDown option:selected').val() },
        type: "post",
        cache: false,
    }).done(function(data){
            var modelDropDown = $('#modelDropDown');
            modelDropDown.empty();
            $.each(data["ModelCollection"], function (index, model) {
                modelDropDown.append(
                    $('<option>', {
                        value: model.Value
                    }).text(model.Text)
                );
            });
    }).fail(function(error){
        //Do something with the error response 
    });
});

Hope this helps!

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

Comments

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.