Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Control Equivalent in ASP.NET MVC 4

Tags:

asp.net-mvc

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?

like image 878
JQuery Mobile Avatar asked Oct 03 '12 17:10

JQuery Mobile


People also ask

What is equivalent of user control 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.

Can we use ASP NET controls in MVC?

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.

What is user control in asp net?

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.

What is razor control in MVC?

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.


2 Answers

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.

like image 194
MushinNoShin Avatar answered Oct 17 '22 23:10

MushinNoShin


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.

like image 39
Stefan P. Avatar answered Oct 17 '22 23:10

Stefan P.