How to access current route parameter from url and reference it on a asp.net view page

535 views Asked by At

I just made a new route:

  routes.MapRoute(
  name: "example",
  url: "{example}/{details}/{id}",
  defaults: new { controller = "example", action = "Index", id = UrlParameter.Optional }
  );

The route works fine but I do not know how to reference which "id" I am currently on so I can display the correct information on my "details" view page for said "id" on my route.

For more context, I have my base "example" page where I am displaying users from a database and each has an "ID" associated with them, when their names are clicked, it then grabs said "ID" and goes to /example/details/{user id I just clicked on} (this works) now I need to know how to show the users info for said route.

Controller:

public ActionResult Details()
{
    var example = from a in db.Example
                  where a.ExamplePresent
                  orderby a.ExampleName
                  select a;
    return View(example.ToList());
}

View:

@model List<Example.Areas.ExamplePage.Models.Example>
@{
    ViewBag.Title = "Example Page";
}
1

There are 1 answers

2
ozum.e On BEST ANSWER

If you don't want to create a viewmodel for this case, you can pass the id parameter and list to the view via tuple and reference it in the view as follows:

public IActionResult Details(int id)
{

    var example = from a in db.Example
              where a.ExamplePresent
              orderby a.ExampleName
              select a;
    return View(Tuple.Create(id, example.ToList()));
}

view

@model Tuple<int, List<Example.Areas.ExamplePage.Models.Example>>

@{
    ViewData["Title"] = "Details";
}

<h2>id: @Model.Item1</h2>

And your example list is:

@Model.Item2

A more proper way would be creating a view model for details view and pass your values via the view model:

viewmodel:

public class DetailsViewModel
{
    public int Id {get;set;}
    public IList<Example.Areas.ExamplePage.Models.Example> Examples {get;set;}
}

action:

public IActionResult Details(int id)
{

    var example = from a in db.Example
          where a.ExamplePresent
          orderby a.ExampleName
          select a;
    return View(new DetailsViewModel{ Id = id, Examples = example.ToList() });
}

view:

@model DetailsViewModel

@{
    ViewData["Title"] = "Details";
}

<h2>id: @Model.Id</h2> // your list is @Model.Examples