Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC: Server Controls vs Html class to render controls?

What are the advantages of rendering a control like this:

<% Html.RenderPartial("MyControl") %> or
<%=Html.TextBox("txtName", Model.Name) %>

over the web Forms style:

<uc1:MyControl ID=MyControl runat=server />

I understand that performance can be one reason because no object needs to be created but having the possibility of calling it from the codebehing just to do some basic rendering logic can be very useful.

If this is discouraged then how you are suposed to deal with this scenarios:

  • You need to make the control visible conditionally and you dont want to fill your HTML with rendering logic.

  • You have <input type="text" value="<%= Model.Name %>" /> but you need to check if Model is null because otherways a NullPointerException will raise.

[EDIT] I asked this when I was beginning with ASP MVC, now I see the advantages of the MVC way like in Cristian answer.

like image 698
Santiago Corredoira Avatar asked Dec 28 '25 14:12

Santiago Corredoira


1 Answers

There are a couple of reasons for this. A "traditional" ASP.NET WebForm control encapsulates both the Controller and View aspect of an MVC application and that would be a violation to the pattern. Also by making them extension methods you gain nice abilities such as being able to swap them out with your own implementation and to swap them out for testing

Phil Haack (Program Manager of ASP.NET MVC) talks a bit about this when he got interviewed on the Herdering Code podcast

Episode 24: Phil Haack on the ASP.NET MVC Beta Release (part 1)

http://herdingcode.com/?p=75

Episode 24: Phil Haack on the ASP.NET MVC Beta Release (part 2)

http://herdingcode.com/?p=82

like image 111
TheCodeJunkie Avatar answered Dec 31 '25 19:12

TheCodeJunkie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!