[英]pass RoteData to view by mvc model
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. 我目前正在学习asp.net核心,因此尝试将RouteData添加到我的mvc模型并将其传递给视图,但是当我计算数据值的数量(
@Model.Data.Count
)时,它返回0。我没有想要在我的视图代码中使用ViewBag或@ViewContext.RouteData.Values[key]
。
mvc route MVC路线
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>
}
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: 只要拥有
ViewData
属性,就不需要自己的Dictionary
,但是每次获取object
都应该像这样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);
}
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
. 我想您也有同样的问题-您应该转换值以从
object
获得值。 You get string
property becouse every object has .ToSting()
method. 您将获得
string
属性,因为每个对象都有.ToSting()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.