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

前端 未结 8 1944
半阙折子戏
半阙折子戏 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:48

    I think you can direct use in url action Url.RequestContext.RouteData.Values["id"]

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

    Just my two cents, but I always use view models for passing any data to my views. Even if it's as simple as needing an int like the id.

    Doing this makes accessing this value trivial, as MVC does all the work for you.

    For what it's worth I typically name my view models as such:

    {Controller}{ViewName}ViewModel

    This helps keeps things organized at scale.

    An example:

    // ~/ViewModels/HomeEditViewModel.cs
    public class HomeEditViewModel
    {
      public int Id { get; set; }
    }
    
    // ~/Controllers/HomeController.cs
    public IActionResult Edit(int id)
    {
      return View(new HomeEditViewModel() { Id = id });
    }
    
    // ~/Views/Home/Edit.cshtml
    @model HomeEditViewModel
    
    <h1>Id: @Model.Id</h1>
    
    0 讨论(0)
提交回复
热议问题