I'm trying to send an ajax request with a value that would populate a dropdown list. But it returns as an error when I'm trying to send it to the same page. I've tried setting up the function as a separate controller but that doesn't work either.
Dropdown box which initiates the ajax.
<select id="SCat_Cat" name="SCat_Cat" asp-for="Cat_Id" asp-items="(SelectList)ViewBag.Cat_ID" class="form-control" onchange="funct()">
<option value="0">Select</option>
</select>
ajax script
<script type="text/javascript">
function funct() {
var catvalue = document.getElementById("SCat_Cat").value;
alert(catvalue);
$.ajax(
{
type: "POST",
url: 'Create?CatID=' + catvalue,
success: function (result) {
if (result.success) {
document.getElementById("SCat_SCat").innerHTML = result;
alert("Good");
}
},
error: function (req, status, error) {
alert("Error");
}
});
return false;
}
</script>
Controller code
public async Task<IActionResult> Create(string CatID)
{
ViewBag.Cat_ID = new SelectList(_context.Category, "Cat_ID", "Cat_Name");
if (CatID == null)
{
ViewBag.SCat_ID = new SelectList("");
}
else
{
List<SubCategory> AllSubCategories = _context.SubCategory.ToList();
List<SubCategory> SelectedSubCategories = AllSubCategories.FindAll(a => a.SCat_Cat.Contains(CatID));
ViewBag.SCat_ID = new SelectList(SelectedSubCategories, "SCat_ID", "SCat_Name");
}
var specialists = await userManager.GetUsersInRoleAsync("Specialist");
ViewBag.Specialist_ID = new SelectList(specialists, "Id", "UserName");
return Request.IsAjaxRequest() ? (IActionResult)PartialView() : View();
}
alternative controller code I've tried that handles this separately
public IActionResult CreatePopulateSCat(string CatID)
{
List<SubCategory> AllSubCategories = _context.SubCategory.ToList();
List<SubCategory> SelectedSubCategories = AllSubCategories.FindAll(a => a.SCat_Cat.Contains(CatID));
ViewBag.SCat_ID = new SelectList(SelectedSubCategories, "SCat_ID", "SCat_Name");
return Request.IsAjaxRequest() ? (IActionResult)PartialView("Create") : View();
}