Search code examples
jqueryasp.net-mvcviewdata

Javascript compare ViewData list values with DropDownlist Selected Item


I've searched around for the answer to this question but nothing that completely satisfies what I'm looking for. I have a dropdown list of items. When the user selects an item, I want to compare the selected value, with the items in 2 different lists (both populated from the db and stored in ViewData). That way, I can populate some other form data based on which list items were matched. I want to do this client-side (i.e., using JQuery/Javascript). This post looks like a good start, but I need to compare my 1 value with the items in 2 different lists: Need simple example of how to populate javascript array from Viewdata list


Solution

  • Eventually got an answer to my question. In the form section of my .cshtml file I have:

    @Html.DropDownList("DropDownCompany", (ViewData["DropDownCompanies"] as SelectList), "Select a Company")
    

    In the javascript portion of my .cshtml file I have:

     $('#DropDownCompany').change(function () {
    
    var dropdownvalue = $('#DropDownCompany').val();
    // This is a list of objects
    var str2 = @Html.Raw(Json.Encode(ViewData["CompaniesData"]));
    

    Then, I can later (still within the javascript portion) compare them via:

    // CompanyKey is a field of the CompaniesData class
    for(var i in str2) {
    if (str2[i].CompanyKey == dropdownvalue) {
    // Do Stuff
    }