10

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 Answers 4

22

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice list, but does not help to clarify when to use which.
8

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

1 Comment

what about the controller would you create a specific controller for the shared folder(SharedController)?
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.