Why Call Ajax request not return branches drop down List based on company drop down list selected value?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-05-06T13:50:50.3733333+00:00

I working on MVC razor page with .NET core 7 .I face issue Ajax request not return branches drop down list based on selected value from drop down list company .

with another meaning I need cascade branch drop down list based on company drop down list by using ajax request .

so data display data on branches drop down list will be

select iBranchCode,vBranchDesc from branchs  where companyno=companyno (selected value on drop down list company)

I try but not give me result

1-create model branches

public class Branch
    {
        [Key]
        public string iBranchCode { get; set; }
        public string vBranchDesc { get; set; }
        public string CompanyNo { get; set; }
        public string CompanyName { get; set; }
    }

2- on razor page AddUser.cshtml.cs

public class AddUserModel : PageModel
    {
    [BindProperty]
    public UC.ADC.Core.Entities.SQL.User  User { get; set; }
    private readonly ADCContext _db;
        public AddUserModel(ADCContext db)
        {
            _db = db;
            userModel = new AddUserViewModel();
          
        }
  public void OnGet()
        {
            userModel.Branches  = _db.Branch.ToList();
            userModel.Companies = GetCompanies();
        }
public JsonResult GetRelatedBranches(string companyId)
        {
            var Branches = _db.Branch.Where(p => p.CompanyNo == companyId).ToList();

            return new JsonResult(Branches); 
          
        }
    }

3-on html page of AddUser.cshtml

@page "/AddUser"
@model UC.ADC.Host.Pages.Users.AddUserModel
 <form method="post">
        <div class="form-group row">
            <label for="company-select" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Company</label>
            <div class="col-sm-3">
                <select id="company-select" asp-for="User.CompanyNo" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">
                    <option value="">-- Select Company --</option>
                     @foreach (var company in Model.userModel.Companies)
                     {
       
                        <option value="@company.CompanyNo">@company.CompanyName</option>


                     }
                </select>
            </div>
        </div>

        <div class="form-group row">
            <label for="branch-select" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Branch</label>
            <div class="col-sm-3">
                <select id="branch-select" asp-for="User.iBranchCode" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">
                    <option value="">-- Select Branch --</option>
                 @*   @(model.br == branch.Id ? "selected" : "")*@
                     @foreach (var branch in Model.userModel.Branches)
                    {
                        <option value="@branch.iBranchCode">@branch.vBranchDesc</option>
                    }
                </select>
            </div>
        </div>
</div>
@section scripts {
 <script>
        $(document).ready(function () {
            $('#company-select').change(function () {
                var companyId = $(this).val();
                console.log("company id is" + companyId)
                if (companyId) {
                    $.ajax({
                        url: '@Url.Action("GetRelatedBranches", "AddUserModel")',
                        type: "GET",
                        dataType: "json",
                        data: { companyId: companyId },
                        success: function (data) {
                            console.log("data  is" + data);
                            $('#branch-select').empty();
                            $.each(data, function (i, item) {
                                $('#branch-select').append($('<option>', {
                                    value: item.iBranchCode,
                                    text: item.vBranchDesc
                                }));
                            });
                        }
                    });
                }
            });
        });
    </script> 
}

Expected result when select company then select branches list related must show based on company no

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,383 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,495 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,410 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 27,656 Reputation points
    2023-05-06T17:38:58.46+00:00

    The AJAX URL does not follow the openly published format for calling a Razor Page handler.

    @page "/AddUser"
    @model RazorPagesDemo.Pages.AddUserModelModel
    @{
        ViewData["Title"] = "AjaxDemo";
    }
    
    
    <div>
        <button id="AjaxDemo" type="button">AJAX</button>
    </div>
    
    @section scripts {
        <script>
            $('#AjaxDemo').click(function () {
                var companyId = 'ABC123';
                $.ajax({
                    url: '?handler=RelatedBranches',
                    type: "GET",
                    dataType: "json",
                    data: { companyId: companyId },
                    success: function (data) {
                        console.log(data);
                    }
                });
            });
        </script>
    }
    
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPagesDemo.Pages
    {
        public class AddUserModelModel : PageModel
        {
            public void OnGet()
            {
            }
    
            public JsonResult OnGetRelatedBranches(string companyId)
            { 
                return new JsonResult(new { id = companyId });
            }
        }
    }
    

    If you don't like the ?handler=MethodName URL format the change the route to @page "{handler?}" .

    Introduction to Razor Pages in ASP.NET Core

    @Ahmed Salah Abed Elaziz, as I have suggested in your many other posts, it is much easier to learn the fundamentals than guessing.


2 additional answers

Sort by: Most helpful
  1. Amy2424 10 Reputation points
    2023-05-06T14:02:23.2433333+00:00

    It seems like you are working on an MVC Razor page using .NET Core 7 and you are facing an issue where an AJAX request is not returning a cascading dropdown list of branches based on the selected value from the country dropdown list. You would like to display data on the branches dropdown list that is selected from iBranchCode and vBranchDesc fields from the "Branch" table, where the company number matches the selected value from the company dropdown list.

    In your code, you have defined a "AddUserModel" class that includes a "GetRelatedBranches" method that retrieves a list of branches from the database based on the selected company value. You have also defined a Razor page named "AddUser.cshtml" that includes two dropdown lists: one for selecting the country and the other for selecting the branch. When a user selects a company from the country dropdown list, you want to update the branch dropdown list to display only the branches related to that company.

    To achieve this, you have added a jQuery script that listens to the change event of the company dropdown list and makes an AJAX request to the server to retrieve the related branches. Once the branches are retrieved, the script updates the branch dropdown list with the new options.

    Based on your expected result, when a user selects a company, the branch dropdown list should update to display only the branches related to that company.


  2. Bruce (SqlWork.com) 61,181 Reputation points
    2023-05-06T15:57:19.33+00:00

    You don’t specify what doesn’t work. Did the Ajax call get made? did it return an error? What did the browser debug tools say? Also your Ajax call does not have an error handler.