asp.net core id value in route doesn't work with ajax

房东的猫 提交于 2020-01-17 03:19:47

问题


I am making something like a chat room application, and when you enter a chat room I use the room id to assign messages to that room, I am using Ajax to send and retrieve messages.

Map Route:

config.MapRoute(
    name: "Default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Room", action = "Index" });

Navigation to room:

<a class="btn btn-default" asp-controller="Chat" asp-action="Index" asp-route-id="@room.Id">@room.Name</a>

So when you are in a room the Route is like so "localhost/Chat/{id}"

Chat Controller (for specific room):

[Route("/Chat/{id:int}")]
public IActionResult Index(int id)
{
    return View();
}

[Route("/Chat/{id:int}/GetChat")]
public IActionResult GetChat()
{
    return PartialView("_Chat", _repository.getAllMessages());
}

I am using a value of 1 for the id to test this.

$.ajax({
    url: rootUrl + "Chat/1/GetChat",
    type: "GET",
    traditional: true,
    success: function (data) {
        //do stuff
    },
    error: function () {
        //do stuff
    }

rootUrl is set in _Layout like so

rootUrl = '@Url.Content("~")'

Whats the best way to make AJAX calls work for specific route with an id?

来源:https://stackoverflow.com/questions/40358857/asp-net-core-id-value-in-route-doesnt-work-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!