ASP.NET MVC Core How Can I show the Route Value in Ienumerable View Page?

151 Views Asked by At

I have a simple route...[controller]/{region} in my Index Controller.

So in the url you would see.. http://localhost:51588/Movies/malta (where 'malta' is the region)

And in the code for the subsequent index.cshtml view which list the movies of 'malta' view I have..

@model IEnumerable<MaltaMoviesMVCcore.Models.Movie>

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

Q...I would like to add the 'region' dynamically to the above ["Title"] so it shows as 'Locations - Malta' I've tried.... ViewData["Title"] ="Movies - " @Model.Region; But get an error "IEnumerable does not contain a definition for 'Region'....."

This works fine in a typical 'Details view' where the model is simply....

@model MaltaMoviesMVCcore.Models.Movie and not ienumerable.
2

There are 2 best solutions below

0
Serge On

Create a MovieModelClass:

public class MovieModel
{
public string Region {get; set;}
public IEnumerable<MaltaMoviesMVCcore.Models.Movie> Movies {get; set;}
}

and init it inside of your conroller

Change your model inside of the view :

@model MovieModel

After this you can use

ViewData["Title"] ="Movies - " @Model.Region

You can access your movies list using :

@Model.Movies

//for example
foreach(var movie in @Model.Movies)
{
}
0
kevmull On

Thanks Sergey for your help.

That didn't quite work.

In the end I got the regionname ('MALTA') form the 'Context.Request.Path.Value' ('MOVIES/MALTA'). Initially I tried using Context.Request.Query["RegionName"] but this returned null I know the preferred way is to get it from the model.

Final code...

// Get the last part of Request. Path '/MOVIES/MALTA'
        string path = Context.Request.Path.Value.ToString();
        string regionname = path.Substring(path.LastIndexOf("/") + 1);