Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create reusable control in ASP.NET MVC

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?

like image 994
Fanda Avatar asked Sep 02 '13 07:09

Fanda


2 Answers

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

like image 116
Giannis Paraskevopoulos Avatar answered Oct 18 '22 22:10

Giannis Paraskevopoulos


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

like image 24
syned Avatar answered Oct 18 '22 22:10

syned