locked
jsonresult show undefined in jquery dropdown asp.net core RRS feed

  • Question

  • User2041008840 posted

    In doing cascading dropdown using jquery in asp.net core <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="5" data-gr-id="5">mvc</g>  - but the output is 'undefined' in city dropdown  after change the StateName 
    here is my code

    //Controller.cs
    
    
    public IActionResult Index()
           {
               ViewBag.City = new SelectList(_context.CityMaster, "ID""Name");
               
               ViewBag.StateID = new SelectList(_context.StateMaster, "ID""Name");
               return View();
           }

    public JsonResult GetCityList(int StateID) { List<CityMaster> CityList = _context.CityMaster.Where(x => x.StateID == StateID).ToList(); return Json(CityList); }

    Index.cshtml

    <div class="form-group">
                    <label asp-for="City" class="control-label"></label>
    
    
                    <select asp-for="City" asp-items="ViewBag.City" class="form-control" id="City"></select>
                    <span asp-validation-for="City" class="text-danger"></span>
                </div>
              
                <div class="form-group">
                    <label asp-for="StateID" class="control-label"></label>
                    @*<input asp-for="StateID" placeholder="State" class="form-control" />*@
                    <select asp-for="StateID" asp-items="ViewBag.StateID" class="form-control" id="StateID"></select>
                    <span asp-validation-for="StateID" class="text-danger"></span>
                </div>
    
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script>
    
        //states
        $(document).ready(function () {
            $("#StateID").change(function () {
                $.get("/Customers/GetCityList", { StateID: $("#StateID").val() }, function (data) {
                    $("#City").empty();
    
                    $.each(data, function (index, row)
                    {
                        $("#City").append("<option value='" + row.ID + "'>" + row.Name + "</option>")
                    });
                });
            })
        });
    </script>

    Monday, February 11, 2019 7:45 AM

Answers

  • User475983607 posted

    Make sure the case is correct.  Simply send debug information to the console to verify.  Press F12 in the browser to open dev tools then open the Console view.

    $.get("/Customers/GetCityList", { StateID: $("#StateID").val() }, function (data) {
    	$("#City").empty();
    	console.log(data);
    	$.each(data, function (index, row)
    	{
    	console.log(row);
    		$("#City").append("<option value='" + row.ID + "'>" + row.Name + "</option>")
    	});
    });

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 11, 2019 3:23 PM