How to create reusable control in ASP.NET MVC

2019-03-11 08:38发布

How can/should I create some "custom control" in ASP.NET MVC 3? I have red about partial views, ViewUsersControl, Html.RenderAction, but I still don't know, which way is the proper MVC way for razor views.

If I need to render some ajax component to view, I can imagine to do it by partial view, but what if I want to render section with custom logic?

4条回答
不美不萌又怎样
2楼-- · 2019-03-11 09:21

As you have mentioned that you can use Partial Views. Yes you can use Partial Views, which is the most effective and efficient way.

For Ajax rendering you can always use

     @using (Ajax.BeginForm("Details", new { id = Model.Post.PostId }, new AjaxOptions    
  {

Few of the links you would like to see

Rendering partial view in ASP.Net MVC3 Razor using Ajax

Render Partial Views using JQuery in MVC3

查看更多
闹够了就滚
3楼-- · 2019-03-11 09:24

1) PartialViews

2) Custom Html helpers

3) Child Actions

Update ASP.NET Core:

2) Tag Helpers are preferred way over Custom Html helpers

3) View Components are used instead of Child Actions

查看更多
够拽才男人
4楼-- · 2019-03-11 09:33

You may use

@{Html.RenderPartial("YourCustomView",YourModel);}

For instance, In your Shared folder create a new View and name it "_MyCustomControl"

Then in the code write :

@model YourNameSpace.Models.YourModel

@{
    Layout = null;
}

@*Here write your control's markup*@

Then in your Views where you want to use this "control" you add:

@{Html.RenderPartial("_MyCustomControl",new YourModel { args });}

If you get into trouble with RenderPartial check this out

查看更多
来,给爷笑一个
5楼-- · 2019-03-11 09:35

In addition to all the other answers for this post, I can offer you the use of EditorFor and DisplayFor templates. These are useful when you want to easily render or edit a custom type. It'll handle validation nicely (which can get weird when using partials) and you can nest them recursively (again another feature that isn't obviously handy until you need it).

You can also use Html.RenderAction() or Html.Action() to call another controller action within a view and display the results in-line in the page. This is probably the closest to what you need as it allows you to render a partial, include code in the controller and it also allows for the passing of parameters.

Links to:

DisplayFor and EditorFor Templates

Action and RenderAction

查看更多
登录 后发表回答