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?
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
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
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
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