如何在ASP.NET MVC中创建可重用控件

Fan*_*nda 9 c# asp.net-mvc controls razor asp.net-mvc-3

我怎么能/应该在ASP.NET MVC 3中创建一些"自定义控件"?我有红色的有关部分的意见,ViewUsersControl,Html.RenderAction,但我仍然不知道,哪个方向是正确的MVC方式的剃刀意见.

如果我需要渲染一些ajax组件来查看,我可以想象通过局部视图来做,但是如果我想用自定义逻辑渲染节呢?

syn*_*ned 21

1)PartialViews

2)自定义Html助手

3)儿童行为

更新ASP.NET Core:

2)Tag Helpers是Custom Html helper的首选方式

3)使用视图组件而不是子操作

  • 不错的列表,但无助于澄清何时使用。 (2认同)

Gia*_*los 8

你可以用

@{Html.RenderPartial("YourCustomView",YourModel);}
Run Code Online (Sandbox Code Playgroud)

例如,在您的Shared文件夹中创建一个新View名称并将其命名"_MyCustomControl"

然后在代码中写:

@model YourNameSpace.Models.YourModel

@{
    Layout = null;
}

@*Here write your control's markup*@
Run Code Online (Sandbox Code Playgroud)

然后在你想要使用它的视图中"control"添加:

@{Html.RenderPartial("_MyCustomControl",new YourModel { args });}
Run Code Online (Sandbox Code Playgroud)

如果你遇到麻烦,RenderPartial 请检查一下