How to get the current route ID within a View from the URL (ASP.NET MVC)

前端 未结 8 1943
半阙折子戏
半阙折子戏 2021-01-30 02:27

Within the view that is returned from a URL such as /Controller/Action/1 (assuming the default route of controller/action/id), how can I get access to the ID from within the Vie

相关标签:
8条回答
  • 2021-01-30 02:29

    ViewData is exactly the right way of doing this.

    Your other option would be to pass a model that contains ID to the view.

    Edit: Without knowing exactly what you're tying to do, it's tough to give more specific advise. Why do you need an ID, but not any other model data? Is your controller really only sending the Id field to the view? It's hard to imagine what the scenario is.

    If the ID value is truly the only model information that is being passed to your view, then you could use the ID itself as the model. Then the return value of your action method would be View(id) and you wouldn't need to use ViewData.

    0 讨论(0)
  • 2021-01-30 02:30

    I think this is what you're looking for:

    <%=Url.RequestContext.RouteData.Values["id"]%>
    
    0 讨论(0)
  • 2021-01-30 02:33

    We can pass id as Route Data or QueryString, so to support both of them i recommend this way:

    var routeValues=Url.RequestContext.RouteData.Values;
    var paramName = "id";
    var id = routeValues.ContainsKey(paramName)?
             routeValues[paramName]:
             Request.QueryString[paramName];
    
    0 讨论(0)
  • 2021-01-30 02:38

    If you are using .NET Core

    Use this code

    Url.ActionContext.RouteData.Values["id"]
    
    0 讨论(0)
  • 2021-01-30 02:44

    Simple Answer In Razor:

    @Url.RequestContext.RouteData.Values["id"]
    

    In ASP.NET Core

    @Url.ActionContext.RouteData.Values["id"]
    
    0 讨论(0)
  • 2021-01-30 02:46

    Adding it to the viewdata is the right thing to do. As for how to add it, you could always add a custom ActionFilter which grabs it from the route dictionary and pushes it into the viewdata.

    0 讨论(0)
提交回复
热议问题