ASP.net MVC 向子视图传递数据

使用 RenderPage

加载子视图

@RenderPage("~/Shared/Component/Dialog.cshtml", new { title = "Hello world!", content="Nani?" })

Razor子视图里使用 Page 来获取传递的数据

<div id="dialog" title="@Page.title" style="display: none;">
    <p>
        @Page.content
    </p>
</div>

使用 Html.Partial

加载子视图

@Html.Partial("Component/Dialog", null, new ViewDataDictionary { { "title", "Hello world!" }, { "content", "Nani?" } })

Razor子视图里使用 ViewBag 来获取传递的数据

<div id="dialog" title="@ViewBag.title" style="display: none;">
    <p>
        @ViewBag.content
    </p>
</div>

还有一种方法是指定子视图为强类型 List

使用RouteData,可以实现跨视图,跨Action参数传递

1.Action中设置路由参数

        public ActionResult Index()
        {
            this.ControllerContext.RouteData.Values.Add("time", "2104");
       //或者
            this.RouteData.Values.Add("time","2014");

            return View();
        }

2.视图中获取或设置路由参数

    <div>
        获取路由参数
    @this.Request.RequestContext.RouteData.Values["time"]
    </div>
    @{
        //重新设置路由参数
        this.Request.RequestContext.RouteData.Values["time"] = "2013";
    }
原文地址:https://www.cnblogs.com/tianma3798/p/3972691.html