Search code examples
c#asp.net-mvcasp.net-mvc-4razorasp.net-mvc-viewmodel

Refresh A View/Partial View without using Ajax or Submit in MVC


I have a ViewModel which contains Different Type of List

When first time page is loaded, I wanted to display the List of Data against the drop-down selected.

When the Drop-Down Changes then I want to display List of Data specific to that type.

But I don't want to go to my Controller, as in that Case I need to do the search/query, where as I already have all the types in my View at first.

How Can I Do that?

Any suggestions.

Thanks,


Solution

  • If you dont want to go to the server(ajax\submit) then you will need to download all the data(in the first response) and change the list using javascript.

    When the select box's change occurs, you javascript will need to get the selected value and update the new list to work against it.

    Here's an example:

    HTML:

    <select id="s1"></select>
    <select id="s2"></select>
    

    JS:

    var currData = ["1", "2", "3"];
    var otherData = [
        ["a", "b", "c"],
        ["d", "e", "f"],
        ["g", "h", "i"]
    ]
    
    
    for (var i = 0; i < currData.length; i++) {
        var option = $('<option value="' + currData[i] + '">' + currData[i] + '</option>');
        $("#s1").append(option);
    }
    // s1 and s2 are the same when the page loads.
    $('#s2').html($('#s1').html());
    
    $('#s1').change(function () {
        var idx = currData.indexOf($(this).val());
        var newSelectData = otherData[idx]; // change s2 due to s1's selection
        $('#s2').children().remove(); // clear the s2 select box
        for (var i = 0; i < newSelectData.length; i++) {
            var option = $('<option value="' + newSelectData[i] + '">' + newSelectData[i] + '</option>');
            $("#s2").append(option);
        }
    });
    

    JSFIDDLE.