1

我目前正在学习 asp.net 核心,因此尝试将 RouteData 添加到我的 mvc 模型并将其传递给视图,但是当我计算数据值 () 的数量时,它@Model.Data.Count返回 0。我不想使用 ViewBag 或@ViewContext.RouteData.Values[key]我的视图代码。

mvc 路由

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

我的行动方法

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);
    }

和我的看法

@model Result
.
.
@foreach (var key in Model.Data.Keys)
    {
        <tr><th>@key :</th><td>@Model.Data[key]</td></tr>
    }
4

1 回答 1

2

Dictionary只要您拥有财产,就不需要自己的ViewData财产,但是object每次获得财产时都应该像这样:

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);
    }

在你看来:

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

我想你有同样的问题 - 你应该从object. 你得到string属性是因为每个对象都有.ToSting()方法。

于 2016-11-21T18:29:41.647 回答