38

I'm working on a new ASP.NET MVC 4 app. I'm really trying to do things the "MVC" way. In particular, I'm interested in using the Razor view engine. Please note that I come from a web forms background, so my questions may seem awkward.

I'm trying to learn if there is something equivalent to user controls in MVC? If so, what are they called? If not, what is the recommended way to creating a reusable component in MVC?

3 Answers 3

30

You're looking for @Html.Action and @Html.Partial.

They allow you to either render a partial view or a full blown controller action in a view. This is a common pattern of reuse in MVC land.

Occasionally you would want to make displayFor or editorFor templates, if a controller action is too heavy. The rule of thumb is if you need to do it multiple times on the page and it needs to be posted back in a form, think about doing it in a template.

Controls in asp.net cover a rather large swath which MVC granularizes a bit more.

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

Comments

15

To creating a reusable HTML component in MVC you can create a partial view in the Views/Shared folder and use @HTML.Partial("_PartialViewName") to include it in any other view or partial view. You can find out more about partial views in this article.

3 Comments

You can actually create the partials anywhere; the 'short' syntax that you used there will search the current and the Shared folders. The full app-relative path can load from anywhere (not even just in the Views folder, in fact)
@AndrewBarber, can you expand upon that with a code sample? What would using the app-relative path look like?
@eric @Html.Partial("~/OtherDir/File.cshtml");
0

You could try:

  • Add a View Start _ViewStart.cshtml in Shared folder
  • Make Layout Null (if required) @{ Layout = null; }
  • Call this page where you want like @Html.Partial("_ViewStart")

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.