1

I'm currently learning asp.net core, so tried to add RouteData to my mvc model and pass it to view, however when I count the number of Data values ( @Model.Data.Count ) it returns 0. I don't want to use ViewBag or @ViewContext.RouteData.Values[key] in my view code.

mvc route

app.UseMvc(route =>
        {
            route.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}/{*catchall}");
        });

my action method

public ViewResult List(string id)
    {
        var r = new Result
        {
            Controller = nameof(HomeController),
            Action = nameof(List),
        };

        // var catch=RouteData.Values["catchall"]; this line is working fine
        r.Data["id"] = id ?? "<no value>";
        r.Data["catchall"] = RouteData.Values["catchall"];
        //when I checked r.Data.count it returns 0 even in here
        return View("Result", r);
    }

and my view

@model Result
.
.
@foreach (var key in Model.Data.Keys)
    {
        <tr><th>@key :</th><td>@Model.Data[key]</td></tr>
    }
Payam Asefi
  • 2,677
  • 2
  • 15
  • 26

1 Answers1

2

You don't need your own Dictionary as long as you have ViewData property, but you should cast your object every time you get it like this:

public ViewResult List(string id)
    {
        var r = new Result
        {
            Controller = nameof(HomeController),
            Action = nameof(List),
        };

        ViewData["id"] = id ?? "<no value>";
        ViewData["catchall"] = RouteData.Values["catchall"];

        return View("Result", r);
    }

On your View:

<tr><th>id :</th><td>@(int)ViewData["id"]</td></tr>

I suppose you have the same problem - you should cast value to get it from object. You get string property becouse every object has .ToSting() method.

teo van kot
  • 12,350
  • 10
  • 38
  • 70