What, why or when it is better to choose cshtml vs aspx? - asp.net

I would like to know what, why or when it is better to choose cshtml and what, why or when it is better to choose aspx technologies? What are these two technologies intended for?
Thank you,

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.
This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.
Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.
The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.
Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.
Imagine that you want to get a Human class, and render it. In cshtml files you write:
<div>Name is #Model.Name</div>
While in aspx files you write:
<div>Name is <%= Human.Name %></div>
As you can see, # sign of razor makes mixing code and markup much easier.

While the syntax is certainly different between Razor (.cshtml/.vbhtml) and WebForms (.aspx/.ascx), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).
This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.
Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.

Cshtml files are the ones used by Razor and as stated as answer for this question, their main advantage is that they can be rendered inside unit tests. The various answers to this other topic will bring a lot of other interesting points.

Related

Recommended approach to port to ASP.NET MVC

I think many of us used to face the same question: what's the best practice to port existing web forms App to MVC. The situation for me is that we'll support both web forms and MVC at the same time. It means, we create new features in MVC, while maintaining legacy pages in web forms, and they're all in a same project.
The point is: we want to keep the DRY (do not repeat yourself) principle and reduce duplicate code as much as possible. The ASPX page is not a problem as we only create new features in MVC, but there're still some shared components we want to re-use the both new / legacy pages:
Master page
UserControl
The question here is: Is that possible to create a common master page / usercontrol that could be used for both web forms and MVC? I know that ViewMasterPage inherits from MasterPage and ViewUserControl inherits from UserControl, so it's maybe OK to let both web forms and MVC ASPX page refer to the MVC version. I did some testing and found sometimes it generates errors during the rendering of usercontrols.
Any idea / experience you can share with me? Very appreciate to it.
Background:
This UI project has been created for years and there're 20+ people working on that. Before I start the common master page trial, there're about 50+ web forms pages and only one MVC page. We create new features on MVC, but the old pages keep remaining in web forms.
This situation will keep for a long time, probably because this's a business-driven company so new features are always in a higher priority. This means we need to support both at the same time.
There are several integration problems using ASP.NET MVC master page with web forms pages and user controls. Since the execution pipelines of the two frameworks are not exactly the same it is normal to have some problems.
One of the things I've faced is that web forms uses single interface pattern (it has one <form> tag with runat="server" on the page). In your master page or pages using it you'll have to create this tag yourself if you want to use server controls. Note that this will work for read-only controls. If you need post-back & event handling you'll probably face more problems with event handling and event validation.
Also one trick is to create html helpers that render existing controls to string. You can check this out for more info http://www.abadjimarinov.net/blog/2009/10/29/HowToRenderAspdotNETControlToString.xhtml This is also a partial solution as it will not work with most user controls.
It will be helpful to provide some code or error messages so I can give you more concrete answers. At this level I can only say that the two frameworks are compatible and you can integrate them but this will not be painless and will require some changes in the existing code.
Let me use an analogy
This will sound harsh but will make it easier for me to pass the idea across. Exaggeration helps sometimes because it emphasizes certain things that need to be understood.
Ok. We're using bicycles to get from A to B at the moment. We're considering buying a car but we want to make transition from one to the other as painful as possible. Consider the fact that we enhanced our bike so it uses custom pedals etc. Is it possible that we use these pedals and other enhancements with the new car we're considering?
Essentially it's possible. But without making a huge mess out of it it is definitely not advisable.
Suggested transition is to change pages one by one to use the new technology (new ones of course in the new technology) and not to introduce some MVC functionality to a webforms page. Either MVC or WebForms for a particular user process. Majority of non-UI code can be reused (business services, data access layer code, data/domain model when applicable). But if you're cramming all the code in your code-behinds... Well bad luck for you. If you haven't separated your code you will more or less be repeating code. Unfortunately that's not Asp.net MVC's fault. It's your bad design without SoC.
Don't combine/mix/blend two UI technologies if you're not suicidal. You can go from A->B using either bike or car, but not both at the same time. This means you can have WebForms part of your application and MVC part of it, but not likely on the same page. And this is only possible if you use Web applications not Web sites. Asp.net MVC can't work as a Web site (on demand partial per page compilation).
Re-usability related to my analogy
Bike and car are two UI technologies. What you do or the purpose of you taking the route from A->B is not important. That's business logic. If you're delivering newspapers that's not related to transport. So you can see that other layers can be reused.
Asp.net WebForms vs. MVC
Asp.net WebForms
Server-side controls (web/user) use the event pipeline execution model. Hence they (unless completely presentational nature) have server side events that some code subscribes to. Platform is completely state-full and everything executes in a manner that abstracts the HTTP completely away. Everything looks like you'd be running a desktop application.
Controls usually encapsulate presentation, code (as in server-side and client side script) and style (as in CSS). That's why it's a lot harder to have SoC using WebForms.
Asp.net MVC
This platforms is completely suited for the stateless nature of the HTTP protocol. Every request is completely stateless (unless you store some state data in persistent medium - Session, DB, etc.). There's nothing like an event model. It's basically just presentation of data/information that is able to transfer data to the server (either as GET, POST, DELETE, PUT...). Server side doesn't have any events. It's only able to read that data and act upon it. And return some result (HTML, Script, JSON, ...). No events. No state. No complex abstractions.
Asp.net MVC abstracts away some common scenarios that are related to data. Like automatic conversion to complex object instances and data validation. Everything else is gone.
Asp.net MVC using WebForms
In case you would like to use server-side controls in an MVC application you would be able to put them in your ASPX/ASCX, but they would only be used as pure presentation. You'd provide some data to render. And that's pretty much it. Postbacks wouldn't even work (unless you'd put a submit button on it), because there's no __doPostback client side functionality that would make a POST request to the server. So if there's any server side code that these controls have (even when they didn't initiate a postback) and are related to it's state-full lifetime after they've been loaded, you can say goodbye to them. More or less.
Other than that, you can read a lot about differences between Asp.net WebForms and Asp.net MVC on the internet.
Sharing MasterPages: see this thread.
User Controls:
This is one of the banes of my existence with MVC; in MVC2 and previous revs, there's no direct equivalent to webforms user controls. A sort-of workaround is creating HtmlHelpers - (effectively extension methods to the Html object available in views that return HTML), but that means you'll have to render your HTML in code. Teh suck.
With MVC3 and the Razor view engine, a new class of Html Helpers is available that provides most of the benefits of user controls, including the ability to place them in separate assemblies (and therefore can be used in multiple projects). I'll see if I can dig up an example link, but Scott Guthrie's blog had an example in one of his recent MVC3/Razor posts.
You can do a certain amount of integration between the 2, but you end up with something more complex & less satisfactory from either approach. A comprise in other words.
I've had this same problem in the past & server side includes worked for me. Old school I know & not something I'd generally recommend. But we don't work in an ideal world.

ASP.NET MVP vs ASP.NET MVC

My company is trying to make an informed decision about how to pursue future development.
We seem to have narrowed down our future internal and external Applications to being web applications. But we are still a bit confused from that point.
There is a large amount of support for Sharepoint here. As I understand it, Sharepoint is basically ASP.NET using MVP.
Others want to use normal ASP.NET using the newer MVC style.
I am also told that these don't easily play well together.
It is looking like Sharepoint (and ASP.NET MVP) is going to be the winner. Before we go that direction, I wanted to ask:
If we choose to base the next 5-10 years of our development efforts off of Sharepoint (ie ASP.NET and MVP) what are we giving up? And is it a big deal or just some "nice to haves" that we are loosing.
(It would have to be a fairly big deal to get management to change direction now.)
Whatever happens, WebForms will turn into a big ugly mess at some point. If you have to use webforms, don't use the postback and page lifycycle model - have aspx pages with presenters for get requests, and have a handler or empty aspx per post. It'll feel a lot more like MVC that way
I would say that what you choose depends heavily upon who your developers are, and what kind of apps you intend to build.
If you build largely crud-like apps that make a lot of use of third party (or your own) custom controls, then staying with Webforms is probably a good idea.
If you build largely "web" style apps with lots of client-side functionality, then MVC is a much better choice.
If you have largely newbie developers, Webforms may be better. If you have more experienced developers, even if they're new to asp.net then MVC may be a better choice.
If you are building very data-centric applications with complex interconnections, then MVC may be a better choice.
There are lots of reasons why you might choose one or the other, and it's always "it depends on...".
Also, MVC and Webforms are not completely incompatible. You can't use them in the same page, but you can use both in the same site. Also, like the comment above says, Sharepoint is not Webforms or MVP per se.. it's kind of it's own thing that is based on webforms. It's very "Webpart" oriented, which is just a way of saying you build lots of custom controls.
I have been a strong proponent of Separation of Concern (SOC) being built into software whether you use MVVM, MVC or MVP all three patterns are quite nice. With this being completely specific to ASP.NET, I would state you should use MVC3.
I have been a .NET developer for years now and have written my MVP pattern that is built on top of StructureMap (lots on my blog about it) and for a while I never saw the benefit of dealing with the changes associated from leaving webforms to goto MVC. However after dealing with ASP.NET for so long I've just had it with ASP.NET webforms errors that are completely out of my control.
The main errors from webforms occur with the ViewState timing out resulting in the generic cryptographic exception and the 2nd is where the ViewState is just truncated by the client or post somehow resulting in legitimate cryptographic errors. With MVC these errors just aren't applicable anymore. With .NET4 I attempted to create a webforms application without ViewState with the new features they added in .NET4 and that completely didn't work which cemented by decision that webforms time is past.
Out of MVC, MVC2 and MVC3 the feature set that comes with the MVC3 and the Razor view-engine is the most robust. You get all of the enhancements that came with MVC2 along with the much cleaner Views that the Razor view engine lets you create, on top of that you get global action filters and the baked jQuery client side templating (I'm 90% sure).
I would also approach MVC very similarly to MVVM where I would have 3 distinct sets of entities, my view models, my domain entities and my physical database models. (The last set may, or may not be the domain entities, I've started to realize trying to make your pure domain entities work with your database layer can be suboptimal at advanced stages)
If you are performing page post-backs to handle events, I would suggest MVP as the Presenter would contain the event handlers for all versions of the view (Different user interfaces such as web pages, iPhone, Android, Windows forms), with a uniform behavior. In other words, you would not need to write control events in a code-behind for every view. At least, they'd do nothing more than call the Presenter's event handler method or raise an event the Presenter handles.
If you are creating web applications and heavily using Ajax for page updates, with one or more web views and a cross-browser JavaScript library, such as jQuery, I would recommend MVC.
So it comes down to how you want to handle page events. MVP & MVC both have separation of concerns. MVP is more server based and easier to add multiple UI's and MVC is more client based, for event handling and more web centric.
From my experience, a strongly enforced MVP pattern has been much better for data centric complex LOB applications.
MVP offers greater seperation as your presenters have no knowledge of web centric concepts.
Code coverage is also increased as you have no conditional code in the views.
We have several apps that where the presenter is used between both web and windows apps.
You presenter referes to a complete abstraction of the view, asp.net MVC relies on abstractions of view dependants (HttpContextBase etc.)
That all said you need to design this into web forms, its not out of the box, but if you do it right first time and have developers that understand it and stick to it you end up with a very clean solution.
there are some solid frameworks out there to support MVP in webforms:
http://www.codeguru.com/csharp/.net/net_general/patterns/article.php/c15173
webformsmvp dot com as well.

Improving testability of ASP.NET site without rewriting to MVC or WCSF

I have an ASP.NET web app which is growing.
It is done in traditional web forms. While I would like to convert it WCSF to improve testability, this is time-prohibitive. I have taken the action to only make method calls in ASPX code behind which call the appropriate methods in the classes in App_Code so the spaghetti code is gone, which is good.
What else could I do to improve testability without any fundamental rewrite?
Thanks
Is this a Web Site project? I find Web Applications are more structured and easier to maintain. I'm not sure if they are more testable. Then do use namespaces where a web site does not.
Have you considered using a UI pattern such as MVP? You also might get partial coverage with creating interfaces for your code-behinds and testing against the interface. Watch out for hidden side-effects (changing the state of a dropdown within a method, it hidden behavior).
A book I found helpful was 'Working Effectively with Legacy Code' by Michael Feathers.

How Does ASP.NET Parse Pages?

I'm looking for an article that will dive deep into how ASP.NET works and how it renders controls from XML markup. For example, under the hood, how does ASP.NET take the following markup and have it produce the results we see?
<asp:Label ID="MyLabel"><%= myObject.Text%></asp:Label>
Does anybody know of any article that will dive deep into the inner workings of ASP.NET?
What happens "under the hood" is that each ASP.NET page is compiled into a .NET class, just like any other. Controls (ASCX) are compiled the same way. There is a compiler for ASP.NET markup just like there is a compiler for c# and VB.NET - you can think of the ASP.NET markup as "yet another" language which compiles to native MSIL.
The native ASP.NET markup is handled by the PageParser. You may notice this class has one interesting and very useful method - GetCompiledPageInstance. As it implies, it compiles the page to a native .NET class. This can be overridden (e.g., you could come up with your own markup and write your own parser/compiler). Spark is a popular alternative to ASP.NET markup.
Each class ultimately inherits from Page or Control. Both of these classes have Render() methods which, at the end of the class's executing its custom functionality you have implemented, write HTML to an output stream.
The big difference is that the compilation often happens at a much different time than the c# or VB.NET code. This is not really a technical requirement so much as it is a feature that permits decoupling the presentation .NET language from the functional .NET language. ASPX and ASCX pages are compiled by the ASP.NET runtime when they are requested in the context of a web server. The compiled assemblies are then held in memory until a) the web application shuts down or b) a filesystem change is detected in one of the ASPX files, triggering a recompile.
It is possible to compile your ASPX pages alongside your c#/VB.NET/whatever, so you can deploy the entire application as a single assembly. This has two advantages - one, the obvious ease of deploying a single DLL. Second, it eliminates the LOOOONG wait time that so often accompanies a "first hit" to an ASP.NET web application. Since all the pages are precompiled, the assembly simply needs to be loaded into memory upon first request, instead of compiling each file.
Reflector -> Expand System.Web.UI -> PageParser Class -> decompile -> Enjoy
(Sorry, not trying to be snarky; this is the only way I was able to get a grasp of it myself)
I always like this site...
https://web.archive.org/web/20210304122759/https://www.4guysfromrolla.com/articles/050504-1.aspx (overview)
https://web.archive.org/web/20210411013534/http://www.4guysfromrolla.com/articles/011404-1.aspx (more in-depth)
I need a LMBTFY (Let me Bing that for you). ;P
Anyway, here are some pages:
Compilation and Deployment in ASP.NET 2.0
Inside the ASP.NET 2.0 Code Compilation Model

Tips from ASP.NET MVC and lessons for ASP.NET WebForms developers

What are some helpful things that ASP.NET MVC developers could suggest that would help us ASP.NET WebForms developers to write better code/web apps?
I'm a WebForms guy but with all the new hype around MVC I'd value some comments on helpful tips, tricks and strategies that might be able to be used in a webforms app.
Something that occurred to me a while ago when learning about the new MVC framework, is that WebForms was, I think, an attempt at MVC in many ways. The markup and code-behind comprise View and Controller, and you're left to write your own Model.
This idea goes hand in hand with the important design considerations I gained from learning about MVC. The most important of which is solidifying the core domain of your system as a whole and making sure all common logic is defined at a level that is reusable within this domain. This is your Model, and I like to call the logic that lives at this level Domain Logic (I mix terms, I know). Your Model should be reusable across different applications (a main web/winforms app, winforms apps for utility and configuration, background processing services, web services, etc.). Your applications should stay very specific to their purpose: they consist of Presentation Logic (their views) and Application Logic (their controllers). Anything that crosses the line of needing to be used in other applications is easily classifiable as Domain Logic, and should not be part of the application code for any given application.
I hope that makes sense.
The gist of it is, even if you're not using a pure MVC framework or object model or whatever, this high level look at design can be applied with great effect. Isolate common logic in a domain layer that is reusable across applications and your applications are much easier to write and extend and maintain.
Forget about page life cycle
There is no ViewState (by default that is)
There are no postbacks
You need to know the HTTP protocol basics (GET/POST). The same goes with HTML (DropDownList is actualy a tag)
I would recommend geting started by watching the screencasts on Microsoft's Learn site:
ASP.NET MVC Videos
There you will learn the differences between the WebForms postback model, and the way that MVC directly routes your URLs to Actions & Methods.
The second major difference is to remember that in ASP.NET MVC you do not use controls that do postbacks. It might feel a bit more like Classic ASP where code is inline on the page within server side blocks, but it is worth it. You will have full control over the HTML that is generated, and this is very good for things like Search Engine Optimization.
Some advices
Don't use standard controls. Instead pay attention jQuery, MooTools.
Use strongly typed Models
It's good practice to use some IoC like Spring.NET
I'm also coming from webforms, but have been learning asp.net MVC since around preview 3.
I'm not exactly sure how to bring anything from MVC into webforms, they are two entirely different frameworks. I'm probably too new with it to understand how any of it could be applied to webforms, but right now it seems they have very little in common.
Some of the strengths of MVC are it's rigid structure on how you need to do things and where you put code. It also does away with the form runat=server and I believe does not promote the usage of any of the asp.net server controls (you need to write all the HTML yourself). That is pretty much the definition of webforms right there. MVC pretty much replaces webforms with it's own framework.
If you ever did Classic ASP or PHP, I would call ASP.net MVC a more structured framework for what people might do with those older scripting languages. It's kind of like the FuseBox framework, but even more structured and evolved.

Resources