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?
In ASP.Net you need to register one tagprefix and then use the user control by tagprefix registered but in ASP.Net MVC using simple Thml. RenderPartial we can use the user control.
There is no viewstate and postback in ASP.NET MVC, so most of server controls will not work. There is set of MVC server controls in ASP.NET MVC RC that don't use postback nor viewstate and so they work fine.
User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. Custom controls. A custom control is a class that you write that derives from Control or WebControl.
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With