I have an asp.net core 3.1 application. In startup file, I have the following route.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
endpoints.MapControllers();
endpoints.MapRazorPages();
});
I have position controller with index and details view.
public class PositionController : Controller
{
private readonly IPositionRepository repository;
public Position Position { get; set; }
public PositionController(IPositionRepository repository)
{
this.repository = repository;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Details(int id)
{
if (id < 0)
return View();
Position = await repository.FindPositionById(id);
if (Position == null)
return RedirectToAction("_NotFound");
return View(Position);
}
Index view points to https://localhost:44356/Position, Details view points to https://localhost:44356/Position/1. (position has id=1)
I have a web api to fetch all the positons data with Get and GetTaskGroups actions.
[Produces("application/json")]
[Route("api/positions")]
[ApiController]
public class PositionsController : Controller
{
private readonly IPositionRepository repository;
public PositionsController(IPositionRepository repository)
{
this.repository = repository;
}
[HttpGet]
public async Task<IActionResult> Get()
{
return Json(new { data = await repository.GetPositions() },
new JsonSerializerSettings() { MetadataPropertyHandling = MetadataPropertyHandling.Ignore
});
}
[HttpGet("{posId}/tasks")]
public async Task<IActionResult> GetTaskGroups(int posId)
{
return Json(new { data = await repository.GetTaskGroups(posId) });
}
I am fetching data with jQuery ajax calls as follows.
function loadPositions() {
positions =
$('#positionsList').DataTable({
"ajax": {
"url": "api/positions",
"type": "get",
"datatype": "json"
},...
function loadTaskGroups(posId) {
taskGroups =
$('#taskGroups').DataTable({
"ajax": {
"url": `/api/positions/${posId}/tasks`,
"type": "get",
"datatype": "json"
},...
I can fetch data for Index view, but, not for Details view. The web api route points to https://localhost:44356/Position/Details/1/api/positions/1/tasks which should point to https://localhost:44356/api/positions/1/tasks. The reason is that I fetch data for the Index view with the following route https://localhost:44356/api/positions/
I think, the problem is related to the default route. Index views does not show up in the url, but details view does.
2
Answers
try so
You only need to delete the "
/
" in the ajax url in theloadTaskGroups
method.Here is the test result: