asp.net-mvc ASP.NET MVC 4 中的用户控件等效项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12714071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User Control Equivalent in ASP.NET MVC 4
提问by JQuery Mobile
I'm working on a new ASP.NET MVC 4 app. I'm really trying to do things the "MVC" way. In particular, I'm interested in using the Razor view engine. Please note that I come from a web forms background, so my questions may seem awkward.
我正在开发一个新的 ASP.NET MVC 4 应用程序。我真的很想以“MVC”的方式做事。特别是,我对使用 Razor 视图引擎很感兴趣。请注意,我来自网络表单背景,所以我的问题可能看起来很尴尬。
I'm trying to learn if there is something equivalent to user controls in MVC? If so, what are they called? If not, what is the recommended way to creating a reusable component in MVC?
我正在尝试了解是否有与 MVC 中的用户控件等效的东西?如果有,他们叫什么?如果没有,在 MVC 中创建可重用组件的推荐方法是什么?
回答by MushinNoShin
You're looking for @Html.Actionand @Html.Partial.
您正在寻找@Html.Action和@Html.Partial。
They allow you to either render a partial viewor a full blown controller actionin a view. This is a common pattern of reuse in MVC land.
它们允许您在视图中渲染局部视图或完整的控制器动作。这是 MVC 领域中常见的重用模式。
Occasionally you would want to make displayFor or editorFor templates, if a controller action is too heavy. The rule of thumb is if you need to do it multiple times on the page and it needs to be posted back in a form, think about doing it in a template.
有时,如果控制器操作太重,您可能想要制作displayFor 或 editorFor 模板。经验法则是,如果您需要在页面上多次执行此操作,并且需要以表单形式发回,请考虑在模板中执行此操作。
Controls in asp.net cover a rather large swath which MVC granularizes a bit more.
asp.net 中的控件涵盖了相当大的范围,MVC 将其细化了一点。
回答by Stefan P.
To creating a reusable HTML component in MVC you can create a partial view in the Views/Sharedfolder and use @HTML.Partial("_PartialViewName")to include it in any other view or partial view. You can find out more about partial views in this article.
要在 MVC 中创建可重用的 HTML 组件,您可以在Views/Shared文件夹中创建一个局部视图,并用于@HTML.Partial("_PartialViewName")将其包含在任何其他视图或局部视图中。您可以在本文中找到有关部分视图的更多信息。

