I am just starting out with ASP.net and Razor Pages. In the code snippet below, my aim is to populate the District dropdown list based on the selected value from the State dropdown list. This is what I have managed to come up with so far:
View:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascirpt" type="text/javascript">
function GetDist(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#select-state").html(procemessage).show();
var url = "/Info/GetDistById/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Quận/Huyện</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#select-state").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<div class="col-md-offset-0 col-md-2">
<select class="form-control" id="select-state" onchange = "javascript:GetDist(this.value);">
@foreach (var state in Model.tbState)
{
<option <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483e29243d2d75083b3c293c2d661b3c293c2d012c">[email protected]</a>>@state.Statename</option>
}
</select>
</div>
<div class="col-md-1 ">Quận/Huyện: </div>
<div class="col-md-offset-0 col-md-2">
<select class="form-control" id="select-dist">
@foreach (var dist in Model.tbDistrict)
{
<option <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e197808d9484dca185889295cfa588929593888295a885">[email protected]</a>>@dist.Districtname</option>
}
</select>
</div>
In my cshtml.cs file, I have the following code. I have used System.Web.Helpers
at the beginning of the code:
public IActionResult GetDistById(int stateid)
{
List<TbDistrict> list = new List<TbDistrict>();
foreach (var q in tbDistrict)
{
if (q.StateId == stateid)
list.Add(q);
}
SelectList selectlist = new SelectList(list, "", "", 0);
JsonResult result = Json(selectlist);
return result;
}
I discovered that the Json() method only functions with the Controller
class in MVC, and not with a Razor PageModel
class. This leads to error CS0103 "The name 'Json' does not exist in the current context". Is there a workaround to resolve this issue?