How to update SelectListItem based on Filtered Category from another DropDown menu in MVC AspNet 6 Razor Syntax



Question: How do you implement a filter of the dropdown menu in Razor MVC SelectedListItem using an Html Razor Tag: @Html.DropDownList ?
Every time I call the function the Dropdown menu does not update with the latest SelectListItems.

Answer: If you are using one form and one of the form elements for filtering then make sure that element e.g. the dropdown menu Html Element has an Event Handler such as onchange="callBack('+passInValue+')" this will call a JavaScript function then pass in the argument. The JavaScript function will then reroute the request to the Function on the Server side. See the code below:

//Front End Side
<form action="toYourFunctionThatWillProcessTheWholeForm">
@html.DropDown("Name", cars,"Select one Item",new {@class="styles"})
@html.DropDown("Name2", cars,"Select one Item",new {@class="styles",@onchange="callBack()"})
</form>

<script>
function callBack(){
var selected = $('#Name').val();
window.location.href = "/MyFunctionAtServerSide"/+selected; //This will get or fetch from MyFunction url, make sure you mark the function with [HttpGet]
//directive otherwise the routing table in Asp.Net will get confused on the url.
}
</script>