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

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

    Id: @Model.Id

提交回复
热议问题