Old webform page in MVC masterpage for quick conversion - asp.net-mvc

I was wondering if anyone had any experience using a webform page with a MVC MasterPage or even better a Razor _Layout page.
The company wants to convert to MVC but they don't want to feel any pain and they want to be able to retro fit their old pages very easily. After the typical grumbling about investment in infrastructure and extensibility I realize that I need to get them on the platform and then work them into the modern era slowly. It's not optimal but it's a foot in the door.
So what I'm hoping is that I can build there masterpage ( header, menu, footer ) into MVC ( actually already have ) and then remove the masterpage from their webform pages and load them in the MVC layout or masterpage.
I figure I can do that with ajax, but I would really like to not have to write wiring for this to happen as a) they will see this as overhead and hacky ( and I agree ) and b) there are a ton of old pages and I don't want to be at it forever.
Any thoughts or experiences would be appreciated,
R

you can try use HttpHandler or HttpModule and at the end of request put section via replace("[SECTION_NAME]", getSection). In MVC you can geberate html from vew and model, but for this you need execute request to server. So i think it will be bette if you cached this part... some like that.

OK, so this was a fool's errand, clearly. The premise was sound, get their regular pages into an mvc masterpage then you have sufficient buy in to move forward. But it's a colossal pain in the ass and possibly not even doable. Perhaps in the future when they have assimilated WebForms in MVC, which is their plan although I can't see how it's possible or even desirable, but not now.
I got some of the way courtesy of this post. It actually loaded up the page in the MVC ( had to be webforms, not razor ) MasterPage. But when the WebForm did it's ridiculous "post back" pseudo-event thing it called the controller, rather then the page. At which point I threw up my hands and decided to go the political route rather then the back door route.
Like I said in the future this maybe possible, and if you really want to dig it may be possible today, but as the cutting and rather snide comments point out it's kind of a dumb idea to begin with.
R

Related

MVC vs ASPX dynamic page render

I have a CMS website written in aspx 2.0 that allows users to build up pages by dropping controls on a page and setting properties (reflection on the server side) and events (client side js). The render engine knows what property to call on each control to find out what to save into the database. I went through all the pitfalls of control re-hydration and lack of proper ids on the controls and really struggled to make the solution SEO friendly which currently is partial at best. Also suffer from viewstate getting huge so I have started to look at MVC as a better way forwards for the next version. The final design of the page is only set when the user decides to promote it live, and may make many changes per day.
A typical page may have many textbox controls, radio button groups, checkbox groups, dropdownlists and images. Also we have a few of our own controls that we reflect at runtime into the solution.
From my initial research into MVC, this looks to have been written to avoid these types of issues and not try to hide the html which looks very promising as well as giving final markup that is much more cross browser friendly.
Now the question - since the requirements are to generate dynamic pages with dynamic html controls, is this a step too far for MVC and I should stick with ASPX, or is there a way to generate the dynamic content which would be suitable for a non technical person to be able to do?
Really appreciate any guidance before I jump in with both feet :)
Thanks
Mark
I'm assuming by aspx 2.0 you mean WebForms? It's really not a question of if MVC is capable of doing what you need - it is capable, and in
my opinion it's more capable. However There are some major differences between WebForms and MVC check out this post for more on that topic: MVC versus WebForms.
I hope this helps. Without more information on exactly what you're trying to accomplish, there's not much more I can say. Consider asking more specific questions with some code examples.
Some of the main advantages of MVC: Clean HTML, No ViewState written on the page, easier to support html5 and thus SEO as well.
For me, since I used MVC 3 years ago I don't even want to touch WebForms thesedays.
Btw, if you want CMS + MVC, why not use Orchard rather than building yourself?
http://paulmason.biz/?p=118

ASP.NET MVC - How to explain it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to teach ASP.NET MVC to students (undergrads) that have been studying ASP.NET for the last 8 weeks (I know that doesn't sound like much time, but the class is 4 hours per day, 5 days per week with Labs, Quizzes, Exams, and Wrestles).
I haven't gotten the question yet...but I know it is coming...
When would I use MVC instead of ASP??
I don't have any real experience with ASP MVC and I can't find any sort of clear-cut answer on the web. Arguments such as "...the web is stateless and ASP MVC is a closer match etc etc" do not mean much to them. They are starting to notice that ASP has lots of controls that seem to simplify their markup compared to MVC.
I'm trying to give an honest spin, and any feedback would be much appreciated!
TIA
Statelessness is a good one word to explain as already highlighted by the members.
Apart from this ask the following questions to the students?
If they have to do the following with ASP.NET (no MVC), how easy will it be?
Test your views
Mock Http objects.
Viewstate reduction (by design)(
Substitute lightweight viewengine for .aspx.
Thorough separation of concerns.
Clean HTML
etc. etc..
Now explain asp.net mvc in the above context. There may be more to it.
Atleast I think they will get the point, thought this may not be applicable to all project, but what's the harm if we are only gaining from this.
To me, the MVC approach is a very different paradigm from the ASP Forms API. I think the idea of being "stateless" is a good way to explain a very broad topic in one word actually.
One of the major advantages that I've seen is that the MVC framework gives a lot of control over the design and the output of your page. For small projects, this may not be the best use of it, but for large projects, it scales very well because you can make different architectural choices that (personally) I find to be better, such as the way that the MVC framework separates logic from the view.
Also, if you're designing a site that has a lot of Javascript, the control you gain over output in the MVC framework can be very helpful because you don't have to worry so much about how IDs and other markup may be rendered, like you typically do in the ASP Forms framework.
The MVC framework is really a totally different way to design web sites. Personally, I think it is more beneficial for large projects, but I also started out in web languages where MVC was a more popular design choice to begin with.
That's just my 2 cents.
I always thought the ASP.NET MVC Framework was a bad name since its a Design Pattern.
The question should be :
When would I use ASP.NET MVC Framework over ASP.NET Web forms?
The Developer Experience
a) ASP.NET Web Forms tries to abstract away the stateless nature of HTTP from the developer. The state of GUI Elements, and or data is stored in the Viewstate/Session. Everyone Form does a postback to itself, basically mimicking the behavior of a WinForm event driven design.
b) HTML GUI Elements are further abstracted by Controls which can be re-used, bought from 3rd party vendors. This helps developers glue an HTML app together without to much JavaScript and HTML/HTTP Knowledge. Basically similar to the way you would develop VB / WinForms
c) You can do a good job implementing the MVC/MVP pattern in ASP.NET webforms. Look at the Patterns and Practices Web Client software factory to see how they did it.
d) Developing using WebForms you are generally changing the HTML (View) based on user feedback at the server. Most events (user clicks a button, edits a field) are handled at the server in a continuous postback loop executing whats called the ASP.NET Page Lifecycle.
VS
Browser controlled view (dont know what else to call it). All changes to the HTML based on user input is handled in the browser. You will be manipulating the DOM with Javascript.
Note: I basing this on the fact that ASP.NET MVC is most likely driven by basic HTML + Ajax
How I would personally choose between them (never having used MVC, just reading on it)
1) If I was to build a pure stateless front end using Ajax, Jquery, EXT JS type libraries ASP.NET MVC would seem the better fit. Although you could build this in ASP.NET Webforms it seems pointless since you not taking advantage of the Postback model and Server Controls.
2) If I were asked to build a new basic web application, I would stick with ASP.NET Webforms since i'm already familiar with it and know the whole page lifecylce.
3) If I were asked to build a Web 2.0 (hate that term) to have a next gen User Experience, I would probably go with ASP.NET MVC, and use JQuery / ASP.NET Ajax client controls.
4) Many companies have built up a solid set of WebForm controls to use. It would be costly to rebuild them all in a pure stateless ajaxy way :)
For someone with experience (and pains) in Winforms - the biggest difference is no more Viewstate. The state of controls on the form is kept on the client, in the browser and sent to the server for each request.
If you use Javascript, it is easier to make changes on the browser side, while the server side gets an easy way to look at the form as a whole without having to recreate controls binding.
Beyond all the nice things MVC provides - separation of view/code, testability - this was for me the key point to move to MVC.
Apart from all the other excellent responses already listed. Webforms is an abstraction away from HTML.
When you want a html table of data, you put a "gridview" control on a page - what you end up with is "gridview" html, and quite possibly not exactly what you were after.
The shoe fits 90% of the time, but a lot of the time, especially when things move beyond a basic site that the controls don't fit. Using Webforms often means that you don't have full control over the final output that is rendered to the browser.
You can of course extend, or write your own grid control. But wouldn't you just prefer to write the html you want instead?
It's my experience that has the projects get more complex, and UI's get more complicated that you end up fighting webforms more and more often.
http://www.emadibrahim.com/2008/09/07/deciding-between-aspnet-mvc-and-webforms/

Does anyone beside me just NOT get ASP.NET MVC? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I've been fiddling with ASP.NET MVC since the CTP, and I like a lot of things they did, but there are things I just don't get.
For example, I downloaded beta1, and I'm putting together a little personal site/resume/blog with it. Here is a snippet from the ViewSinglePost view:
<%
// Display the "Next and Previous" links
if (ViewData.Model.PreviousPost != null || ViewData.Model.NextPost != null)
{
%> <div> <%
if (ViewData.Model.PreviousPost != null)
{
%> <span style="float: left;"> <%
Response.Write(Html.ActionLink("<< " + ViewData.Model.PreviousPost.Subject, "view", new { id = ViewData.Model.PreviousPost.Id }));
%> </span> <%
}
if (ViewData.Model.NextPost != null)
{
%> <span style="float: right;"> <%
Response.Write(Html.ActionLink(ViewData.Model.NextPost.Subject + " >>", "view", new { id = ViewData.Model.NextPost.Id }));
%> </span> <%
}
%>
<div style="clear: both;" />
</div> <%
}
%>
Disgusting! (Also note that the HTML there is temporary placeholder HTML, I'll make an actual design once the functionality is working).
Am I doing something wrong? Because I spent many dark days in classic ASP, and this tag soup reminds me strongly of it.
Everyone preaches how you can do cleaner HTML. Guess, what? 1% of all people look at the outputted HTML. To me, I don't care if Webforms messes up my indentation in the rendered HTML, as long as I have code that is easy to maintain...This is not!
So, convert me, a die hard webforms guy, why I should give up my nicely formed ASPX pages for this?
Edit: Bolded the "temp Html/css" line so people would stfu about it.
Compared to Web Forms, MVC is simultaneously a lower-level approach to HTML generation with greater control over the page output and a higher-level, more architecturally-driven approach. Let me capture Web Forms and MVC and show why I think that the comparison favors Web Forms in many situations - as long as you don't fall into some classic Web Forms traps.
Web Forms
In the Web Forms model, your pages correspond directly to the page request from the browser. Thus, if you are directing a user to a list of Books, you'll likely have a page somewhere called "Booklist.aspx" to which you'll direct him. In that page, you'll have to provide everything needed to show that list. This includes code for pulling data, applying any business logic, and displaying the results. If there is any architectural or routing logic affecting the page, you'll have to code the architectural logic on the page as well. Good Web Forms development usually involves the development of a set of supporting classes in a separate (unit-testable) DLL. These class(es) will handle business logic, data access and architectural/routing decisions.
MVC
MVC takes a more "architectural" view of web application development: offering a standardized scaffold upon which to build. It also provides tools for automatically generating model, view and controller classes within the established architecture. For example, in both Ruby on Rails (just "Rails" from here on out) and ASP.NET MVC you'll always start out with a directory structure that reflects their overall model of web application architecture. To add a view, model and controller, you'll use a command like Rails's "Rails script/generate scaffold {modelname}" (ASP.NET MVC offers similar commands in the IDE). In the resulting controller class, there will be methods ("Actions") for Index (show list), Show, New and Edit and Destroy (at least in Rails, MVC is similar). By default, these "Get" Actions just bundle up the Model and route to a corresponding view/html file in the "View/{modelname}" directory (note that there are also Create, Update and Destroy actions that handle a "Post" and route back to Index or Show).
The layout of directories and files is significant in MVC. For example, in ASP.NET MVC, the Index method for a "Book" object will likely just have one line: "Return View();" Through the magic of MVC, this will send the Book model to the "/View/Books/Index.aspx" page where you'll find code to display Books. Rails's approach is similar although the logic is a bit more explicit and less "magic." A View page in an MVC app is usually simpler than a Web Forms page because they don't have to worry as much about routing, business logic or data handling.
Comparison
The advantages of MVC revolve around a clean separation of concerns and a cleaner, more HTML/CSS/AJAX/Javascript-centric model for producing your output. This enhances testability, provides a more standardized design and opens the door to a more "Web 2.0" type of web site.
However, there are some significant drawbacks as well.
First, while it is easy to get a demo site going, the overall architectural model has a significant learning curve. When they say "Convention Over Configuration" it sounds good - until you realize that you have a book's-worth of convention to learn. Furthermore, it is often a bit maddening to figure out what is going on because you are relying on magic rather than explicit calls. For example, that "Return View();" call above? The exact same call can be found in other Actions but they go to different places. If you understand the MVC convention then you know why this is done. However, it certainly doesn't qualify as an example of good naming or easily understandable code and it is much harder for new developers to pick up than Web Forms (this isn't just opinion: I had a summer intern learn Web Forms last year and MVC this year and the differences in productivity were pronounced - in favor of Web Forms). BTW, Rails is a bit better in this regard although Ruby on Rails features dynamically-named methods that take some serious getting-used-to as well.
Second, MVC implicitly assumes that you are building a classic CRUD-style web site. The architectural decisions and especially the code generators are all built to support this type of web application. If you are building a CRUD application and want to adopt a proven architecture (or simply dislike architecture design), then you should probably consider MVC. However, if you'll be doing more than CRUD and/or you are reasonably competent with architecture then MVC may feel like a straightjacket until you really master the underlying routing model (which is considerably more complex than simply routing in a WebForms app). Even then, I've felt like I was always fighting the model and worried about unexpected outcomes.
Third, if you don't care for Linq (either because you are afraid that Linq-to-SQL is going to disappear or because you find Linq-to-Entities laughably over-produced and under powered) then you also don't want to walk this path since ASP.NET MVC scaffolding tools are build around Linq (this was the killer for me). Rails's data model is also quite clumsy compared to what you can achieve if you are experienced in SQL (and especially if you are well-versed in TSQL and stored procedures!).
Fourth, MVC proponents often point out that MVC views are closer in spirit to the HTML/CSS/AJAX model of the web. For example, "HTML Helpers" - the little code calls in your vew page that swap in content and place it into HTML controls - are much easier to integrate with Javascript than Web Forms controls. However, ASP.NET 4.0 introduces the ability to name your controls and thus largely eliminates this advantage.
Fifth, MVC purists often deride Viewstate. In some cases, they are right to do so. However, Viewstate can also be a great tool and a boon to productivity. By way of comparison, handling Viewstate is much easier than trying to integrate third-party web controls in an MVC app. While control integration may get easier for MVC, all of the current efforts that I've seen suffer from the need to build (somewhat grody) code to link these controls back to the view's Controller class (that is - to work around the MVC model).
Conclusions
I like MVC development in many ways (although I prefer Rails to ASP.NET MVC by a long shot). I also think that it is important that we don't fall into the trap of thinking that ASP.NET MVC is an "anti-pattern" of ASP.NET Web Forms. They are different but not completely alien and certainly there is room for both.
However, I prefer Web Forms development because, for most tasks, it is simply easier to get things done (the exception being generation of a set of CRUD forms). MVC also seems to suffer, to some extent, from an excess of theory. Indeed, look at the many questions asked here on SO by people who know page-oriented ASP.NET but who are trying MVC. Without exception, there is much gnashing of teeth as developers find that they can't do basic tasks without jumping through hoops or enduring a huge learning curve. This is what makes Web Forms superior to MVC in my book: MVC makes you pay a real world price in order to gain a bit more testability or, worse yet, to simply be seen as cool because you are using the latest technology.
Update: I've been criticized heavily in the comments section - some of it quite fair. Thus, I have spent several months learning Rails and ASP.NET MVC just to make sure I wasn't really missing out on the next big thing! Of course, it also helps ensure that I provide a balanced and appropriate response to the question. You should know that the above response is a major rewrite of my initial answer in case the comments seem out of synch.
While I was looking more closely into MVC I thought, for a little while, that I'd end up with a major mea culpa. In the end I concluded that, while I think we need to spend a lot more energy on Web Forms architecture and testability, MVC really doesn't answer the call for me. So, a hearty "thank you" to the folks that provided intelligent critiques of my initial answer.
As to those who saw this as a religious battle and who relentlessly engineered downvote floods, I don't understand why you bother (20+ down-votes within seconds of one another on multiple occasions is certainly not normal). If you are reading this answer and wondering if there is something truly "wrong" about my answer given that the score is far lower than some of the other answers, rest assured that it says more about a few people who disagree than the general sense of the community (overall, this one has been upvoted well over 100 times).
The fact is that many developers don't care for MVC and, indeed, this is not a minority view (even within MS as the blogs seem to indicate).
MVC gives you more control over your output, and with that control comes greater risk of writing poorly designed HTML, tag soup, etc...
But at the same time, you have several new options you didn't have before...
More control over the page and the elements within the page
Less "junk" in your output, like the ViewState or excessively long IDs on elements (don't get me wrong, I like the ViewState)
Better ability to do client side programming with Javascript (Web 2.0 Applications anyone?)
Not just just MVC, but JsonResult is slick...
Now that's not to say that you can't do any of these things with WebForms, but MVC makes it easier.
I still use WebForms for when I need to quickly create a web application since I can take advantage of server controls, etc. WebForms hides all the details of input tags and submit buttons.
Both WebForms and MVC are capable of absolute garbage if you are careless. As always, careful planning and well thought out design will result in a quality application, regardless if it is MVC or WebForms.
[Update]
If it is any consolation as well, MVC is just a new, evolving technology from Microsoft. There has been many postings that WebForms will not only remain, but continue to be developed for...
http://haacked.com
http://www.misfitgeek.com
http://rachelappel.com
... and so on...
For those concerned about the route MVC is taking, I'd suggest giving "the guys" your feedback. They appear to be listening so far!
Most of the objections to ASP.NET MVC seems centered around the views, which are one of the most "optional" and modular bits in the architecture. NVelocity, NHaml, Spark, XSLT and other view engines can be easily swapped out (and it's been getting easier with every release). Many of those have MUCH more concise syntax for doing presentation logic and formatting, while still giving complete control over the emitted HTML.
Beyond that, nearly every criticism seems to come down to the <% %> tagging in the default views and how "ugly" it is. That opinion is often rooted in being used to the WebForms approach, which just moves most of the classic ASP ugliness into the code-behind file.
Even without doing code-behinds "wrong", you have things like OnItemDataBound in Repeaters, which is just as aesthetically ugly, if only in a different way, than "tag soup". A foreach loop can be much easier to read, even with variable embedding in the output of that loop, particularly if you come to MVC from other non-ASP.NET technologies. It takes much less Google-fu to understand the foreach loop than to figure out that the way to modify that one field in your repeater is to mess with OnItemDataBound (and the rat's nest of checking if it's the right element to be changed.
The biggest problem with ASP tag-soup-driven "spaghetti" was more about shoving things like database connections right in between the HTML.
That it happened to do so using <% %> is just a correlation with the spaghetti nature of classic ASP, not causation. If you keep your view logic to HTML/CSS/Javascript and the minimal logic necessary to do presentation, the rest is syntax.
When comparing a given bit of functionality to WebForms, make sure to include all of the designer-generated C#, and the code-behind C# along with the .aspx code to be sure that the MVC solution is really not, in fact, much simpler.
When combined with judicious use of partial views for repeatable bits of presentation logic, it really can be nice and elegant.
Personally, I wish much of the early tutorial content focused more on this end of things than nearly exclusively on the test-driven, inversion of control, etc. While that other stuff is what the experts object to, guys in the trenches are more likely to object to the "tag soup".
Regardless, this is a platform that is still in beta. Despite that, it's getting WAY more deployment and non-Microsoft developers building actual stuff with it than most Microsoft-beta technology. As such, the buzz tends to make it seem like it's further along than the infrastructure around it (documentation, guidance patterns, etc) is. It being genuinely usable at this point just amplifies that effect.
<% if (Model.PreviousPost || Model.NextPost) { %>
<div class="pager">
<% if (Model.PreviousPost) { %>
<span><% Html.ActionLink("<< " + Model.PreviousPost.Subject, "view")); %></span>
<% } if (Model.NextPost) { %>
<span><% Html.ActionLink(Model.NextPost.Subject + " >>", "view")); %></span>
<% } %>
</div>
<% } %>
You can make another post asking how to do this without including the embeded CSS.
NOTE: ViewData.Model becomes Model in the next release.
And with the aid of a user control this would become
<% Html.RenderPartial("Pager", Model.PagerData) %>
where PagerData is initialized via an anonymous constructor in the action handler.
edit: I'm curious what your WebForm implementation would look like for this problem.
I am not sure at what point people stopped caring about their code.
HTML is the most public display of your work, there are a LOT of developers out there who use notepad, notepad++, and other plain text editors to build a lot of websites.
MVC is about getting control back from web forms, working in a stateless environment, and implementing the Model View Controller design pattern without all the extra work that normally takes place in an implementation of this pattern.
If you want control, clean code, and to use MVC design patterns, this is for you, if you don't like working with markup, don't care about how malformed your markup gets, then use ASP.Net Web Forms.
If you don't like either, you are definitely going to be doing just about as much work in the markup.
EDIT
I Should also state that Web Forms and MVC have their place, I was in no way stating that one was better than the other, only that each MVC has the strength of regaining control over the markup.
I think you are missing some things. First, there's no need for the Response.Write, you can use the <%= %> tags. Second, you can write your own HtmlHelper extensions to do common actions. Third, a little bit of formatting helps a lot. Fourth, all of this would probably be stuck in a user control to be shared between several different views and thus the overall mark up in the main view is cleaner.
I'll grant you that the mark up is still not as neat as one would like, but it could be cleaned up considerably through the use of some temporary variables.
Now, that's not so bad and it would be even better if I didn't have to format it for SO.
<%
var PreviousPost = ViewData.Model.PreviousPost;
var NextPost = ViewData.Model.NextPost;
// Display the "Next and Previous" links
if (PreviousPost != null || NextPost != null)
{
%>
<div>
<%= PreviousPost == null
? string.Empty
: Html.ActionLinkSpan("<< " + PreviousPost.Subject,
"view",
new { id = PreviousPost.Id },
new { style = "float: left;" } ) %>
<%= NextPost == null
? string.Empty
: Html.ActionLinkSpan( NextPost.Subject + " >>",
"view",
new { id = NextPost.Id },
new { style = "float: right;" } ) %>
<div style="clear: both;" />
</div>
<% } %>
Please have a look at Rob Conery's post I Spose I’ll Just Say It: You Should Learn MVC
The big deal with MVC is that it's a conceptual framework that has been around a long time, and it has proven itself as a productive, powerful way to build both web applications and workstation applications that scale horizontally and vertically. It goes directly back to the Alto and Smalltalk. Microsoft is late to the party. What we have now with ASP.NET MVC is really primitive, because there's so much catching up to do; but damn, they're pouring out new releases fast and furiously.
What was the big deal with Ruby on Rails? Rails is MVC. Developers have been converting because, by word of mouth, it's become the way for programmers to be productive.
It's a huge deal; MVC and the implicit endorsement of jQuery are tipping points for Microsoft accepting that platform-neutral is critical. And what's neutral about it, is that unlike Web Forms, Microsoft can't lock you in conceptually. You can take all your C# code and reimplement in another language entirely (say PHP or java - you name it) because it's the MVC concept that's portable, not the code itself. (And think how huge it is that you can take your design and implement it as a workstation app with little code change, and no design change. Try that with Web Forms.)
Microsoft has decided that Web Forms will not be the next VB6.
The two main advantages of the ASP.NET MVC framework over web forms are:
Testability - The UI and events in web forms are next to impossible to test. With ASP.NET MVC, unit testing controller actions and the views they render is easy. This comes with a cost in up-front development cost, but studies have shown that this pays off in the long run when it comes time to refactor and maintain the app.
Better control over rendered HTML - You state that you don't care about the rendered HTML because nobody looks at it. That's a valid complaint if that were the only reason to have properly formatted HTML. There are numerous reasons for wanting properly formatted HTML including: SEO, the ability to use id selectors more often (in css and javascript), smaller page footprints due to lack of viewstate and ridiculously long ids (ctl00_etcetcetc).
Now, these reasons don't really make ASP.NET MVC any better or worse than web forms in a black-and-white sort of way. ASP.NET MVC has its strengths and weaknesses, just like web forms. However, the majority of complains about ASP.NET MVC seem to stem from a lack of understanding on how to use it rather than actual flaws in the framework. The reason your code doesn't feel right or look right might be because you have several years of web forms experience under your belt and only 1-2 months of ASP.NET MVC experience.
The problem here isn't so much that ASP.NET MVC rocks or sucks, it's that it's new and there's very little agreement as to how to use it correctly. ASP.NET MVC offers much more fine-grained control over what's occurring in your app. That can make certain tasks easier or harder depending on how you approach them.
Hey, I've been struggling with switching to MVC as well. I am absolutely not a fan of classic ASP and MVC rendering reminds me a lot of those days. However, the more I use MVC, the more it grows on me. I am a webforms guy (as many are) and spent the past several years getting used to working with datagrids, etc. With MVC that is taken away. HTML Helper classes are the answer.
Just recently I spent 2 days trying to figure out the best way to add paging to a "grid" in MVC. Now, with webforms I could whip this out in no time. But I will say this... once I had the paging helper classes built for MVC, it became extremely simple to implement. To me, even easier than webforms.
That being said, I think that MVC will be much more developer friendly when there are a consistent set of HTML Helpers out there. I think we are going to start seeing a ton of HTML helper classes pop up on the web in the near future.
It's funny because that's what I said when I first saw webforms.
I'll admit that I don't get asp.net MVC yet. I'm trying to use it in a side project I'm doing but it's going pretty slow.
Besides not being able to do things that were so easy to do in web forms I notice the tag soup. It really does seem to take a step backwards from that perspective. I keep hoping that as I learn it will get better.
So far I've noticed that the top reason to use MVC is to gain full control over your HTML. I also read that asp.net MVC is able to serve up more pages faster than web forms and probably related to this, the individual page size is smaller than an average web forms page.
I really don't care what my HTML looks like as long as it works in the major browsers, but I do care how fast my pages load and how much bandwidth they take up.
While I fully agree that that is ugly markup, I think using the ugly view syntax to write off ASP.NET MVC as a whole is not fair. The view syntax has gotten the least attention from Microsoft, and I am fully expecting something to be done about it soon.
Other answers have discussed the benefits of MVC as a whole, so I will focus on the view syntax:
The encouragement to use Html.ActionLink and other methods that generate HTML is a step in the wrong direction. This smacks of server controls, and, to me, is solving a problem that doesn't exist. If we are going to generate tags from code, then why bother using HTML at all? We can just use DOM or some other model and build up our content in the controller. Ok, that sounds bad, doesn't it? Oh yes, separation of concerns, that is why we have a view.
I think the correct direction is to make the view syntax as much like HTML as possible. Remember, a well designed MVC should not only give you separation of code from content, it should let you streamline your production by having people who are expert in layout work on the views (even though they do not know ASP.NET), and then later as a developer you can step in and make the view mockup actually dynamic. This can only be done if if the view syntax looks very much like HTML, so that the layout folks can use DreamWeaver or whatever the current popular layout tool is. You might be building dozens of sites at once, and need to scale in this way for efficiency of production. Let me give an example of how I could see the view "language" working:
<span mvc:if="ViewData.Model.ShowPrevious" style="float: left;">
<a mvc:inner="ViewData.Model.PreviousPost.Subject" href="view/{ViewData.Model.PreviousPost.Id}">sample previous subject</a>
</span>
<span mvc:if="ViewData.Model.ShowNext" style="float: left;">
<a mvc:inner="ViewData.Model.NextPost.Subject" href="view/{ViewData.Model.NextPost.Id}">sample next subject</a>
</span>
<div mvc:if="ViewData.Model.ShowNextOrPrevious" style="clear: both;" />
This has several advantages:
looks better
more concise
no funky context switching betwen HTML and <% %> tags
easy to understand keywords that are self-explanatory (even a non-programmer could do this - good for parallelization)
as much logic moved back into controller (or model) as possible
no generated HTML - again, this makes it very easy for someone to come in and know where to style something, without having to mess around with Html. methods
the code has sample text in it that renders when you load the view as plain HTML in a browser (again, good for layout people)
So, what exactly does this syntax do?
mvc:inner="" - whatever is in the quotes gets evaluated and the inner HTML of the tag gets replaced with the resulting string. (Our sample text gets replaced)
mvc:outer="" - whatever is in the quotes gets evaluated and the outer HTML of the tag gets replaced with the resulting string. (Again, sample text gets replaced.)
{} - this is used for inserting output inside of attributes, similar to <%= %>
mvc:if="" - insde the qoutes is the boolean expression to be evaulated. The close of the if is where the HTML tag gets closed.
mvc:else
mcv:elseif="" - ...
mvc:foreach
Now, I can only speak for myself here:
IMO, if you're a die-hard (anything) then conversion isn't for you. If you love WebForms that's because you can accomplish what you need to, and that's the goal of any too.
Webforms does a good job of abstracting HTML from the developer. If that's your goal, stick with Web Forms. You have all the wonderful "click and drag" functionality that has made desktop development what it is today. There are many included controls (plus a wealth of third party controls) that can bring about different functionality. You can drag a "grid" that's directly associated with a DataSource from your database; it comes with built in inline-editing, paging, etc.
As of right now, ASP.NET MVC is very limited in terms of third party controls. So again, if you like Rapid Application Development, where a lot of functionality is wired up for you, you should not try to get converted.
With all of this said, this is where ASP.NET shines:
- TDD. Code is not testable, nuff said.
Separation of concerns. That is the backbone of the MVC pattern. I am fully aware that you can accomplish this in Web Forms. However, I like imposed structure. It was too easy in Web Forms to mix design and logic. ASP.NET MVC makes it easier for different members of a team to work on different sections of the application.
Coming from somewhere else: My background is CakePHP and Ruby on Rails. So, it is clear where my bias lies. It's simply about what you're comfortable with.
Learning Curve: To expand on the last point; I hated the idea of "templating" to change the functionality of different elements. I didn't like the fact that a lot of the design was accomplished in the code behind file. It was one more thing to learn, when I was already intimately familiar with HTML and CSS. If I want to do something in an "element" on the page, I stick in a "div" or "span", slap an ID on it and off I go. In Web Forms I would have to go research how to do this.
Current State of Web "Design": Javascript libraries like jQuery are becoming more commonplace. The way that Web Forms mangles your IDs just makes implementation (outside of Visual Studio) more difficult.
More Separation (Design): Because a lot of the design is wired into your controls, it would be very difficult for an outside designer (without Web Forms) knowledge to work on a Web Forms project. Web Forms was built to be the end all and be all.
Again, much of these reasons stem from my unfamiliarity with Web Forms. A Web Forms project (if designed right) can have "most" of the benefits of ASP.NET MVC. But that's the caveat: "If designed right". And that's just something I don't know how to do in Web Forms.
If you're doing stellar work in Web Forms, you're efficient and it works for you, that's where you should stay.
Basically, do a quick review on both (try to find a unbiased source [good luck]) with a list of pros and cons, evaluate which one fit your goals and pick based on that.
Bottom line, pick the path of least resistance and most benefit to meet your goals. Web Forms is a very mature framework and will only get better in the future. ASP.NET MVC is simply another alternative (to draw in Ruby on Rails and CakePHP developers such as myself :P )
Java EE's JSPs looked like this when they were first proposed - ugly scriptlet code.
Then they offered up tag libraries to make them more HTML tag-ish. The problem was that anybody could write a tag library. Some of the results were disastrous, because people embedded a lot of logic (and even style) into tag libraries that generated HTML.
I think the best solution is the JSP Standard Tag Library (JSTL). It's "standard", HTML tag-ish, and helps prevent people from putting logic into pages.
An added benefit is that it preserves that line of demarcation between web designers and developers. The good sites that I see are designed by people with an aesthetic sense and designing for usability. They lay out pages and CSS and pass them on to developers, who add in the dynamic data bits. Speaking as a developer who lacks these gifts, I think we give something important away when we ask developers to write web pages from soup to nuts. Flex and Silverlight will suffer from the same problem, because it's unlikely that designers will know JavaScript and AJAX well.
If .NET had a path similar to JSTL, I'd advise that they look into it.
Just thought I'd share how this sample looks with the shiny new Razor view engine which is default since ASP .NET MVC 3.
#{
var prevPost = ViewData.Model.PreviousPost;
var nextPost = ViewData.Model.NextPost;
}
#if (prevPost != null || nextPost != null) {
<div>
#if (prevPost != null) {
<span style="float: left;">
#Html.ActionLink("<< " + prevPost.Subject, "view", new { id = prevPost.Id })
</span>
}
#if (nextPost != null) {
<span style="float: left;">
#Html.ActionLink(nextPost.Subject + " >>", "view", new { id = nextPost.Id })
</span>
}
<div style="clear: both;" />
</div>
}
Any problem with that?
Also, you shouldn't actually inline your CSS styles, should you? And why do you check for nullity in three places instead of just two? An extra div rarely hurts. This is how I'd do it:
<div>
#if (prevPost != null) {
#Html.ActionLink("<< " + prevPost.Subject, "view",
new { id = prevPost.Id, #class = "prev-link" })
}
#if (nextPost != null) {
#Html.ActionLink(nextPost.Subject + " >>", "view",
new { id = nextPost.Id, #class = "next-link" })
}
<div class="clear" />
</div>
I can't speak directly to the ASP.NET MVC project, but generally speaking MVC frameworks have come to dominate web application development because
They offer a formal separation between Database Operations,"Business Logic", and Presentation
They offer enough flexibility in the view to allow developers to tweak their HTML/CSS/Javascript to work in multiple browsers, and future versions of those browsers
It's this last bit that's the important one. With Webforms, and similar technologies, you're relying on your vendor to write your HTML/CSS/Javascript for you. It's powerful stuff, but you have no guarantee that the current version of Webforms is going to work with the next generation of web browsers.
That's the power of the view. You get full control over your application's HTML. The downside is, you need to be disciplined enough to keep the logic in your views to a minimum, and keep the template code as simple as you possibly can.
So, that's the trade-off. If Webforms are working for you and MVC isn't, then keep using Webforms
Most of my frustration with it is just not knowing how to do things "properly". Since it was released as a preview we've all had a bit of time to look at things, but they've been changing quite a bit. At first I was really frustrated but the framework seems workable enough to enable me to create extremely complex UI's (read: Javascript) pretty quickly. I understand that you can do this with Webforms as I was doing it before but it was a huge pain in the butt trying to get everything to render correctly. A lot of times I would end up using a repeater to control the exact output and would end up with a lot of the spaghetti mess that you have above as well.
In an effort to not have the same mess, I've been using a combination of having domain, service layers, and a dto to transfer to the view. Put that together with spark, a view engine and it gets really nice. It takes a bit to setup but once you get it going, I've seen a big step up in the complexity of my applications visually, but its so stinking simple to do code wise.
I wouldn't probably do it exactly like this but here's your example:
<if condition="myDtp.ShowPager">
<div>
<first />
<last />
<div style="clear: both;" />
</div>
</if>
That's pretty maintainable, testable, and tastes yummy in my code soup.
The takeaway is that clean code is really possible, but it's a big ass shift from the way we were doing things. I don't think everyone groks it yet though. I know I'm still figuring it out...
Steve Sanderson's recently published book 'Pro ASP.NET MVC' [1] [2] from Apress suggests another alternative -- creating a custom HtmlHelper extension. His sample (from Chapter 4 on page 110) uses the example of a paged list, but it can easily be adapted for your situation.
public static string PostNavigator(this HtmlHelper html, Post previous, Post next, Func<int, string> pageUrl)
{
StringBuilder result = new StringBuilder();
if (previous != null || next != null)
{
result.Append("<div>");
if (previous != null)
{
result.Append(#"<span class=""left"">");
TagBuilder link = new TagBuilder("a");
link.MergeAttribute("href", pageUrl(previous.Id));
link.InnerHtml = String.Format("<< {0}", html.Encode(previous.Subject));
result.Append(link.ToString());
result.Append("</span>");
}
if (next != null)
{
if (previous != null)
{
result.Append(" ");
}
result.Append(#"<span class=""right"">");
TagBuilder link = new TagBuilder("a");
link.MergeAttribute("href", pageUrl(next.Id));
link.InnerHtml = String.Format("{0} >>", html.Encode(next.Subject));
result.Append(link.ToString());
result.Append("</span>");
}
result.Append("</div>");
}
return result.ToString();
}
You would call it in your view with code something like this:
<%= Html.PostNavigator(ViewData.Model.PreviousPost, ViewData.Model.NextPost, id => Url.Action("View", new { postId = id })) %>
[1] http://blog.codeville.net/2009/04/29/now-published-pro-aspnet-mvc-framework-apress/
[2] http://books.google.com/books?id=Xb3a1xTSfZgC
I was hoping to see a post from Phil Haack, but it wasnt here so I just cut and paste it from
http://blog.wekeroad.com/blog/i-spose-ill-just-say-it-you-should-learn-mvc/ in the comments section
Haacked - April 23, 2009 - Rob, you're a riot! :) I do find it funny when people write spaghetti code in MVC and then say "look! Spaghetti!" Hey, I can write spaghetti code in Web Forms too! I can write it in rails, PHP, Java, Javascript, but not Lisp. But only because I can't yet write anything in Lisp. And when I do write spaghetti code I don't look at my plate glumly expecting to see macaroni. The point people often make when comparing it to classic ASP is that with classic ASP people tended to mix concerns. Pages would have view logic with user input handling mixed in with model code and business logic all mixed up in one. That's what the spaghetti was about! Mixing concerns all in one big mess. With ASP.NET MVC, if you follow the pattern, you're less likely to do it. Yeah, you still might have a bit of code in your view, but hopefully that's all view code. The pattern encourages you to not put your user interaction code in there. Put it in the controller. Put your model code in a model class. There. No spaghetti. It's O-Toro Sushi now. :)
Me too; I would spend my time on Silverlight rather than ASP.NET MVC.
I have tried MVC 1.0 and have had a look at the latest 2.0 Beta 1 release a few day ago.
I (can)'t feel that how ASP.NET MVC is better than webform.
The selling point of MVC are:
Unit (test)
Separate the design (view) and logic (controller + model)
No viewstate and better element id management
RESTful URL and more ...
But webform, by using code-behind.Theme, Skin, and Resource are already perfect to separate the design and logic.
Viewstate: client id management is coming on ASP.NET 4.0. I am only concerned about unit tests, but unit tests are not enough being a reason to turn me to ASP.NET MVC from webform.
Maybe I can say: ASP.NET MVC is not bad, but webform is already enough.
I've been using MVC for since Preview 3 came out and while it is still has it's growing pains it helps quite a bit in the area of team development. Try having three people work on a single webforms page and then you'll understand the concept of banging your head on the wall. I can work with a developer who understands the design elements on the view page and our resident Linq god in making the model work while I put everything together in the controller. I've never been able to develop in a realm where the separation of concerns was so easy to achieve.
Biggest selling point of ASP.Net MVC - StackOverflow runs on the MVC stack.
That being said... your code is so much prettier than what I normally do with the view page. Also, one of the guys I work with is working on wrapping the HTML helper into a tag library. Instead of <%=Html.RandomFunctionHere() %> it works like
< hh:randomfunction / >
I just hope the MVC team gets around to it at some point because I'm sure they'd do a better job of it.
Use a Facade Pattern to wrap all the logic for all the data you need to display and then use it as your generic in your view and then.... no more spaghetti code.
http://en.wikipedia.org/wiki/Design_pattern_(computer_science)
If you need more help cgardner2020#gmail.com
The implementation ASP.NET MVC is horrible. The product plain sucks. I've seen several demos of it and I'm ashamed of MSFT... I'm sure the guys who wrote it are smarter than me, but it's almost as if they don't know what the Model-View-Controller is.
The only people I know who are trying to implement MVC are people who like to try new things from MSFT. In the demos I've seen, the presenter had an apologetic tone...
I'm a big fan of MSFT, but I have to say that I see no reason to bother with their implementation of MVC. Either use Web Forms or use jquery for web development, don't choose this abomination.
EDIT:
The intent of the Model-View-Controller architectural design pattern is to separate your domain from the presentation from the business rules. I've used the pattern successfully in every Web Forms project I've implemented. The ASP.NET MVC product does not lend itself well to the actual architectural design pattern.

Should I migrate to ASP.NET MVC?

I just listened to the StackOverflow team's 17th podcast, and they talked so highly of ASP.NET MVC that I decided to check it out.
But first, I want to be sure it's worth it. I already created a base web application (for other developers to build on) for a project that's starting in a few days and wanted to know, based on your experience, if I should take the time to learn the basics of MVC and re-create the base web application with this model.
Are there really big pros that'd make it worthwhile?
EDIT: It's not an existing project, it's a project about to start, so if I'm going to do it it should be now...
I just found this
It does not, however, use the existing post-back model for interactions back to the server. Instead, you'll route all end-user interactions to a Controller class instead - which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views).
How would that work? No viewstate? No events?
If you are quite happy with WebForms today, then maybe ASP.NET MVC isn't for you.
I have been frustrated with WebForms for a really long time. I'm definitely not alone here. The smart-client, stateful abstraction over the web breaks down severely in complex scenarios. I happen to love HTML, Javascript, and CSS. WebForms tries to hide that from me. It also has some really complex solutions to problems that are really not that complex. Webforms is also inherently difficult to test, and while you can use MVP, it's not a great solution for a web environment...(compared to MVC).
MVC will appeal to you if...
- you want more control over your HTML
- want a seamless ajax experience like every other platform has
- want testability through-and-through
- want meaningful URLs
- HATE dealing with postback & viewstate issues
And as for the framework being Preview 5, it is quite stable, the design is mostly there, and upgrading is not difficult. I started an app on Preview 1 and have upgraded within a few hours of the newest preview being available.
It's important to keep in mind that MVC and WebForms are not competing, and one is not better than the other. They are simply different tools. Most people seem to approach MVC vs WebForms as "one must be a better hammer than the other". That is wrong. One is a hammer, the other is a screwdriver. Both are used in the process of putting things together, but have different strengths and weaknesses.
If one left you with a bad taste, you were probably trying to use a screwdriver to pound a nail. Certain problems are cumbersome with WebForms that become elegant and simple with MVC, and vice-versa.
I have used ASP.NET MVC (I even wrote a HTTPModule that lets you define the routes in web.config), and I still get a bitter taste in my mouth about it.
It seems like a giant step backwards in organization and productivity. Maybe its not for some, but I've got webforms figured out, and they present no challenge to me as far as making them maintainable.
That, and I don't endorse the current "TEST EVERYTHING" fad...
ASP.NET MVC basically allows you to separate the responsibility of different sections of the code. This enable you to test your application. You can test your Views, Routes etc. It also does speed up the application since now there is no ViewState or Postback.
BUT, there are also disadvantages. Since, you are no using WebForms you cannot use any ASP.NET control. It means if you want to create a GridView you will be running a for loop and create the table manually. If you want to use the ASP.NET Wizard in MVC then you will have to create on your own.
It is a nice framework if you are sick and tired of ASP.NET webform and want to perform everything on your own. But you need to keep in mind that would you benefit from creating all the stuff again or not?
In general I prefer Webforms framework due to the rich suite of controls and the automatic plumbing.
I would create a test site first, and see what the team thinks, but for me I wouldn't go back to WebForms after using MVC.
Some people don't like code mixed with HTML, and I can understand that, but I far prefer the flexibility over things like Page Lifecycle, rendering HTML and biggy for me - no viewstate cruft embedded in the page source.
Some people prefer MVC for better testibility, but personally most of my code is in the middle layer and easily tested anyway...
#Juan Manuel Did you ever work in classic ASP? When you had to program all of your own events and "viewstatish" items (like a dropdown recalling its selected value after form submission)?
If so, then ASP.NET MVC will not feel that awkward off the bat. I would check out Rob Conery's Awesome Series "MVC Storefront" where he has been walking through the framework and building each expected component for a storefront site. It's really impressive and easy to follow along (catching up is tough because Rob has been reall active and posted A LOT in that series).
Personally, and quite contrary to Jeff Atwood's feelings on the topic, I rather liked the webform model. It was totally different than the vbscript/classic ASP days for sure but keeping viewstate in check and writing your own CSS friendly controls was enjoyable, actually.
Then again, note that I said "liked". ASP.NET MVC is really awesome and more alike other web technologies out there. It certainly is easier to shift from ASP.NET MVC to RAILS if you like to or need to work on multiple platforms. And while, yes, it is very stable obviously (this very site), if your company disallows "beta" software of any color; implementing it into production at the this time might be an issue.
#Jonathan Holland I saw that you were voted down, but that is a VERY VALID point. I have been reading some posts around the intertubes where people seem to be confusing ASP.NET MVC the framework and MVC the pattern.
MVC in of itself is a DESIGN PATTERN. If all you are looking for is a "separation of concerns" then you can certainly achieve that with webforms. Personally, I am a big fan of the MVP pattern in a standard n-tier environment.
If you really want TOTAL control of your mark-up in the ASP.NET world, then MVC the ramework is for you.
If you are a professional ASP.NET developer, and have some time to spare on learning new stuff, I would certainly recommend that you spend some time trying out ASP.NET MVC. It may not be the solution to all your problems, and there are lots of projects that may benefit more from a traditional webform implementation, but while trying to figure out MVC you will certainly learn a lot, and it might bring up lots of ideas that you can apply on your job.
One good thing that I noticed while going through many blog posts and video tutorials while trying to develop a MVC pet-project is that most of them follow the current best practices (TDD, IoC, Dependency Injection, and to a lower extent POCO), plus a lot of JQuery to make the experience more interesting for the user, and that is stuff that I can apply on my current webform apps, and that I wasn't exposed in such depth before.
The ASP.NET MVC way of doing things is so different from webforms that it will shake up a bit your mind, and that for a developer is very good!
OTOH for a total beginner to web development I think MVC is definitely a better start because it offers a good design pattern out of the box and is closer to the way that the web really works (HTML is stateless, after all). On MVC you decide on every byte that goes back and forth on the wire (at least while you don't go crazy on html helpers). Once the guy gets that, he or she will be better equipped to move to the "artificial" facilities provided by ASP.NET webforms and server controls.
If you like to use server controls which do a lot of work for you, you will NOT like MVC because you will need to do a lot of hand coding in MVC. If you like the GridView, expect to write one yourself or use someone else's.
MVC is not for everyone, specially if you're not into unit testing the GUI part. If you're comfortable with web forms, stay with it. Web Forms 4.0 will fix some of the current shortcomings like the ID's which are automatically assigned by ASP.NET. You will have control of these in the next version.
Unless the developers you are working with are familiar with MVC pattern I wouldn't. At a minimum I'd talk with them first before making such a big change.
I'm trying to make that same decision about ASP.NET MVC, Juan Manuel. I'm now waiting for the right bite-sized project to come along with which I can experiment. If the experiment goes well--my gut says it will--then I'm going to architect my new large projects around the framework.
With ASP.NET MVC you lose the viewstate/postback model of ASP.NET Web Forms. Without that abstraction, you work much more closely with the HTML and the HTTP POST and GET commands. I believe the UI programming is somewhat in the direction of classic ASP.
With that inconvenience, comes a greater degree of control. I've very often found myself fighting the psuedo-session garbage of ASP.NET and the prospect of regaining complete control of the output HTML seems very refreshing.
It's perhaps either the best--or the worst--of both worlds.
5 Reasons You Should Take a Closer Look at ASP.NET MVC
I dont´t know ASP.NET MVC, but I am very familiar with MVC pattern. I don´t see another way to build professional applications without MVC. And it has to be MVC model 2, like Spring or Struts. By the way, how you people were building web applications without MVC? When you have a situation that some kind of validation is necessary on every request, as validating if user is authenticated, what is your solution? Some kind of include(validate.aspx) in every page?
Have you never heard of N-Tier development?
Ajax, RAD (webforms with ajax are anti-RAD very often), COMPLETE CONTROL (without developing whole bunch of code and cycles). webforms are good only to bind some grid and such and not for anything else, and one more really important thing - performance. when u get stuck into the web forms hell u will switch on MVC sooner or later.
I wouldn't recommend just making the switch on an existing project. Perhaps start a small "demo" project that the team can use to experiment with the technology and (if necessary) learn what they need to and demonstrate to management that it is worthwhile to make the switch. In the end, even the dev team might realize they aren't ready or it's not worth it.
Whatever you do, be sure to document it. Perhaps if you use a demo project, write a postmortem for future reference.
I dont´t know ASP.NET MVC, but I am very familiar with MVC pattern. I don´t see another way to build professional applications without MVC. And it has to be MVC model 2, like Spring or Struts. By the way, how you people were building web applications without MVC? When you have a situation that some kind of validation is necessary on every request, as validating if user is authenticated, what is your solution? Some kind of include(validate.aspx) in every page?
No, you shouldn't. Feel free to try it out on a new project, but a lot of people familiar with ASP.NET webforms aren't loving it yet, due to having to muck around with raw HTML + lots of different concepts + pretty slim pickings on documentation/tutorials.
Is the fact that ASP.net MVC is only in 'Preview 5' be a cause for concern when looking into it?
I know that StackOverflow was created using it, but is there a chance that Microsoft could implement significant changes to the framework before it is officially out of beta/alpha/preview release?
If you are dead set on using an MVC framework, then I would rather set out to use Castle project's one...
When that's said I personally think WebControls have a lot of advantages, like for instance being able to create event driven applications which have a stateful client and so on. Most of the arguments against WebControls are constructed because of lack of understanding the WebControl model etc. And not because they actually are truly bad...
MVC is not a Silver Bullet, especially not Microsoft MVC...
I have seen some implementation of MVC framework where for the sake of testability, someone rendered the whole HTML in code. In this case the view is also a testable code. But I said, my friend, putting HTML in code is a maintenance nightmare and he said well I like everything compiled and tested. I didn't argue, but later found that he did put this HTML into resource files and the craziness continued...
Little did he realized that the whole idea of separating View also solved the maintenance part. It outweighs the testability in some applications. We do not need to test the HTML design if we are using WYSWYG tool. WebForms are good for that reason.
I have often seen people abusing postback and viewstate and blaming it on the ASP .NET model.
Remember the best webpages are still the .HTMLs and that's where is the Power of ASP .NET MVC.

What's the best way to implement user controls in ASP.NET MVC?

Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.
I'm wondering about how user controls work in ASP.NET MVC. We have tons of .ASCX controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.
What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.
To implement a user control you do the following call:
<% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %>
You may also see the older syntax which as of PR5 is not valid anymore
<%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %>
You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.
As Nick suggested, you will indeed be able to render your user controls, but obviously the page-cycle, pagestate and postback from traditional ASP Webforms won't work anymore, thus making your controls most likely useless.
I think you'll have to rewrite most of your complex controls to port your website to MVC, while simple controls which, for instance, provide only formatting and have no postback status, should simply work.
The code provided by Nick will simply work in this case.
And about sharing between more projects: I think controls will be more like "reusable HTML-rendering components" that can be shared across a website, rather than "reusable code components" with logic (like WebForms controls). Your web logic will/should be in the pages controllers and not in the HTML controls. Therefore sharing controls across more projects won't be so useful as in the WebForms case.
MVC has different page life cycle compare to your user control.
You may consider this to re-write.
The aspx is the view. You still need a re-write, the syntax is different.
JavaScript will work. But I hardly find the WebControls will work. Because MVC does not have viewstate and postback anymore.
For the code behind (aspx.cs) you need to convert that to be a Controller class.
Page_Load method will no longer works. You probable leave it to Index() method.
Model is simply the entity classes that your code behind consume.
Conclusion, it's a total rewrite. Cheers. Happy coding.
Yeah, you can do RenderPartial. That's a good start. But eventually these guys will need logic and other controller type stuff. Be on the lookout for a subcontroller implementation from the framework team. There should also be something in MvcContrib soon. Or roll your own.
Edit: I just posted about this here: http://mhinze.com/subcontrollers-in-aspnet-mvc/

Resources