开发者

ASP.NET MVC 3: ViewModel for master template?

开发者 https://www.devze.com 2023-03-05 01:52 出处:网络
When I create开发者_StackOverflow中文版d my first empty MVC 3 project, this is the /Views/Shared/_Layout.cshtml file\'s contents:

When I create开发者_StackOverflow中文版d my first empty MVC 3 project, this is the /Views/Shared/_Layout.cshtml file's contents:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>

<body>
    @RenderBody()
</body>
</html>

The first thing I notice is that the <title>@ViewBag.Title</title>. The last thing I want to do is be using a dynamic "ViewBag" instead of a strongly-typed ViewModel.

How do I change my _Layout.cshtml so that the master template uses a strongly-typed ViewModel instead?


You can easily use @model to define the model type, but who will set the master pages's model or create it? The controller handles its own view and the model for the master page will be different based on the model created in each controller.

So, you may want to make all the models you pass to the views inherit from a base model class that has the properties required for master page and make the master page have the base type as the model type, but it'll be too ugly.

I'd suggest live with it for the simple cases like title here, if you find that you do a lot of stuff in there, have your own controller, action and view that perform the shared parts, and call Html.RenderAction() in the master page to get that executed.


http://gurustop.net

0

精彩评论

暂无评论...
验证码 换一张
取 消