您可以使用子操作。
首先编写一个控制器,您可以在其中像往常一样使用依赖注入,其中将包含一个子操作:
public class CopyrightController: Controller
{
private readonly IClock clock;
public CopyrightController(IClock clock)
{
this.clock = clock;
}
[ChildActionOnly]
public ActionResult Index()
{
// In this example I am directly passing the IClock instance
// to the partial view as model but in a real application
// you might want to use a view model here
return PartialView(this.clock);
}
}
然后你可以有一个相应的局部视图(~/Views/Copyright/Index.cshtml
):
@model IClock
<div>Copyright ...</div>
最后在你的 _Layout 中调用这个子动作:
<footer>
@Html.Action("Copyright", "Index")
</footer>