.NET MVC-如何从模型中获取控制器/查看特定数据,而无需使用ViewBag/ViewData

发布于 2025-02-03 05:47:32 字数 1394 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万水千山粽是情ミ 2025-02-10 05:47:32

我有兴趣看到您所面临的问题的特定代码示例,如果您有一个问题?

说一下您所说的话,您对被迫使用ViewBag的可疑是正确的,因为如果我们可以帮助它,这并不是我们应该使用的东西。显然,它在那里,并且可以是一个很好的“脱离监狱卡”,但是坚持查看模型肯定会更好。

您是否考虑过在布局/视图中定义和使用部分?它们本质上像Renderbody的命名版本一样工作。

例如,在您的布局中,您可能会有:

@RenderSection("SideBar", required: false)

可以从您的视图中访问,例如:

@model your.namespace.viewmodel    

... some view cshtml ...

@section SideBar {
    <h4>Related content for @Model.Name</h4>
    ...
}

查看此章节概述,它包含更多深度示例,以及如何在您不想传递任何内容的情况下定义默认的部分内容。

I would be interested to see a specific code example of the problem you're facing, for context, if you have one?

Going on what you've said, you are right to be suspicious that you've been forced into using the ViewBag as it's not really something we should be using if we can help it. Obviously it's there and can be a good "get out of jail free card", but sticking to view models is certainly better.

Have you considered defining and using sections in your layout/view? They essentially work like a named version of RenderBody.

For example, in your Layout you might have:

@RenderSection("SideBar", required: false)

This can be accessed from your view, like this:

@model your.namespace.viewmodel    

... some view cshtml ...

@section SideBar {
    <h4>Related content for @Model.Name</h4>
    ...
}

Check out this overview of sections, it includes more in depth examples and also how to define default section content on the occasions you don't want to pass anything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文