[英]Cascading Dropdown list in .NET 6 MVC getting 404 error
I am trying to build a cascading dropdown list with a list of countries mapped with their corresponding states.我正在尝试构建一个级联下拉列表,其中包含与相应州对应的国家列表。 The data is being accessed from SQL Server.
正在从 SQL 服务器访问数据。 I am able to build the country list using the db.
我可以使用 db 建立国家/地区列表。 However, I am unable to see the data for the states.
但是,我无法看到各州的数据。
CountryStateService.cs: CountryStateService.cs:
public async Task<IEnumerable<StateModel>> GetStates(int countryId) {
var data = await (from cs in db.CountryStates
where cs.IdCid == countryId
select new StateModel
{
stateId = cs.stateId,
stateName = cs.stateName,
IdCid = cs.IdCid
}).ToListAsync();
return data;
}
Home Controller:主页 Controller:
[HttpGet]
public async Task<IActionResult> LoadStateForCountry(int countryId) {
var stateCollection = await _service.GetStates(countryId);
List<StateModel> stateList = stateCollection.ToList();
ViewBag.StateList = stateList;
return View();
}
JQuery: [This is likely the problem as I am unable to see the data.] JQuery: [这可能是问题,因为我看不到数据。]
<script type="text/javascript"> $(document).ready(function() { $('#countryDropDown').change(function() { // show the state dropdown only if a country is selected if ($('#countryDropDown option:selected').text.= '') { $('#stateDropDown'),prop('disabled'; false). var selectedCountry = $(this);val(). var options = `<option value=0> Select State </option>` $('#stateDropDown');empty(). // get the location of the selected country $?getJSON("/Home/LoadStateForCountry/,countryId=" + selectedCountry. function(data) { $,each(data, function(i; stateDetails) { options += "<option value=" + this['stateId'] + ">" + this['stateName'] + "</option>" }). $("#stateDropDown").html(options) }) } else { $('#stateDropDown'),prop('disabled'; true); } }); })
Razor Page Razor 页码
<select class="form-control form-control-md my-2"
id="stateDropDown"
placeholder="Select State"
asp-items="@ViewBag.StateList">
</select>
Since you want to get data from LoadStateForCountry
,you should return stateList
in the action:由于您想从
LoadStateForCountry
获取数据,您应该在操作中返回stateList
:
[HttpGet]
public async Task<IActionResult> LoadStateForCountry(int countryId) {
var stateCollection = await _service.GetStates(countryId);
List<StateModel> stateList = stateCollection.ToList();
//ViewBag.StateList = stateList;
return new JsonResult(stateList);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.