Which way do you prefer to create your forms in MVC? - asp.net-mvc

Which way do you prefer to create your forms in MVC?
<% Html.Form() { %>
<% } %>
Or
<form action="<%= Url.Action("ManageImage", "UserAccount") %>" method="post">
</form>
I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included.
What is your take?

The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.

On the whole, I think I'm kinda old-school as I prefer to roll my own HTML elements.
I also prefer a view engine like like NHaml, which makes writing HTML almost an order of magnitude simpler.

I have to agree with both of you, I am not really like this simplistic WebForms style that seems to be integrating its way in to MVC. This stuff almost seems like it should be a 3rd party library or at the very least an extensions library that can be included if needed or wanted.

I am totally in the opinion of old school HTML, that is what designers use. I don't like to include to much code centric syntax for this reason. I treat the web form view engine like a third party library, because I replaced it with a different view engine. If you do not like the way the web form view model works or the direction it is going, you can always go a different route. That is one of the main reasons I love ASP.NET MVC.

I agree with Andrew Peters, DRY. It should also be pointed out that you can specify your controller, action, and params to the .Form() helper and if they fit into your routing rules then no query string parameters will be used.
I also understand what Will was saying about the V in MVC. In my opinion I do not think it is a problem to put code in the view as long as it is for the view. It is really easy to cross the line between controller and view if you are not careful. Personally I can not stand to use C# as a template engine without my eyes bleeding or getting the urge to murder someone. This helps me keep my logic separated, controller logic in C#, view logic in brail.

The reason for using helpers is that they allow you to encapsulate common patterns in a consistent and DRY fashion. Think of them as a way of refactoring views to remove duplication just as you would with regular code.
For example, I blogged about some RESTful NHaml helpers that can build urls based on a model.

Related

ASP.NET MVC: Am I doing it right?

So I am an old web forms guy and new to the MVC (in general, not only ASP.NET) framework. My views are starting to look a lot like the good old classic ASP. Not that i'm adding any business logic or anything, but more of a presentation logic. I end up with a lot of <% %> tags and if/else statements for deciding links to display or styles to use.
I also thought of deciding the styles or links within the controller and setting them on the model, but sounds like breaking the MVC purpose.
I end up ignoring the <% %> to make sure my HTML is well formed.
I want to hear your opinion. Are your views the same as mine? Am I doing something wrong?
If I have a ton of presentation logic, I try to move that to an extension off the HtmlHelper class.
Along with what mxmissle said (I voted him up) says I will do a partial view to move complex areas of a page to a seperate file, it helps clean things up as well as code reuse.
I find if things are looking a bit too old school ASP it's time to refactor. It's surprising what you can clean up into a helper class or partial view, or simply redo using something more concise.
Edit: Also, if it's looking a bit too old school ASP, perhaps you have logic in your view that doesn't belong there.
I usually create a ViewModel class specific for each view that contains any logic associated with the specific view. This is good for situations where the outcome of a condition is just a simple DIV or SPAN tag which don't really warrant their own extension or partial view.
I find it will clean up a lot of the classic ASP'ish look in my views.
See Stephen Walther's blog for more info on this approach.
Yes, you're doing it right. ASP.NET MVC isn't an improvement over classic web forms in every respect. It has its advantages and disadvantages ("tag soup", as you've discovered, being one of the disadvantages).
There are a few ways to alleviate the pain (moving as much logic into the model, HTML helpers, partial views, etc.), but it's difficult to avoid.

ASP.NET web forms as ASP.NET MVC

I am sorry for possible misleading about the title, but I have no idea for a proper title.
Feel free to edit.
Anyway, I am using ASP.NET Web Forms, and maybe this isn't how web forms is intended to be used, but I like to construct and populate HTML elements manually. It gives me more control.
I don't use DataBinding and that kind of stuff. I use SqlConnection, SqlCommand and SqlDataReader, set SQL string etc. and read the data from the DataReader.
Old school if you like. :)
I do create WebControls so that I don't have to copy-paste every time I need some control, but mostly, I need WebControls to render as HTML so I can append that HTML into some other function that renders the final output with the control inside.
I know I can render a control with control.RenderControl(writer), but this can only be done in (pre)Render or RenderContents overrides.
For example.
I have a dal.cs file where is stored all static functions and voids that communicate with the database.
Functions mostly return string so that it can be appended into some other function to render the final result.
The reason I am doing like this is that I want to separate the coding from the HTML as much as I can so that I don't do <% while (dataReader.Read()) %> in HTML and display the data. I moved this into a CodeBehind.
I also use this functions to render in the HttpHandler for AJAX response.
That works perfectly, but when I want to add a control (ASP.NET Server control (.cs extension, not .ascx)) I don't know how to do that, so I see my self writing the same control as function that returns string or another function inside that control that returns string and replaces a job that would RenderContents do, so that I can call that function when I need control to be appended into a another string.
I know this may not be a very good practice.
As I see all the tutorials/videos about the ASP.NET MVC, I think it suite my needs as with the MVC you have to construct everything (or most of it) by your self, which I am already doing right now with web forms.
After this long intro, I want to ask how can I build my controls so I can use them as I mentioned (return string) or I have to forget about server controls and build the controls as functions and used them that way?
Is that even possible with ASP.NET Server Controls (.cs extension) or am I right when I said that I am not using it right.
To be clear, I am talking about how to properly use a web forms, but to avoid data binders because I want to construct everything by my self (render HTML in Code Behind).
Someone might think that I am appending strings like "some " + "string", which I am not. I am using StringBuilder for that so there's no slowness.
Every opinion is welcome.
You need to stop thinking in terms of "controls" and webforms. MVC is a completely different way of constructing applications.
I also hate the automatic renderers in WebForms, they produce horrible html that never makes any sense. However, you dont want to be writing your html in your codebehind and passing it around as strings, thats just nasty. Your presentation code is mixed in with your logic, AND youre writing HTML in c# strings!!!
So, MVC... Instead of "widgets" that do interacty things with codebehinds and postbacks, yours view ONLY display data and contain forms to allow you to post to the controllers.
Because of this, you can strongly type your views to a Type, and then access the data you pass to it from a controller via the Model property. The equivalent to UserControls are Partial Views (ViewUserControl) which can be used to modularise your rendering code for types. For example, you might make an Address partial to which you pass your Person's Address property every time you need it rendered. This way you aren't repeating html all over the place.
P.S. A single file for all your DAL?
I hope I never ever have to work on an app you wrote in this manner. If your application is string-heavy then something is wrong.
Agree with #sliderhouserules, the way you are using MVC framework is awful. You must forgot all your "old school" techniques.
You should never use SqlCommands, SqlReaders, etc. in the code of the pages. You should pass to the view only a model (e.g. View(bar)) and it will be better if you avoid usage of
ViewData["some magic string"] = bar
Every time when you will use "old school" technique 2 mans and 2 cats will be killed :).
Also it's better to use some ORM (Object-Relational Mapper) like Linq2sql, NHibernate, SubSonic, etc.
If you need in samples of good application design please look at SharpArchitecture. It has a very good architecture and implementation and may help a lot. It has one sample (with Northwind db) and one more sample will be added soon.
Also look at CodeCampServer. It has very good architecture too.
It's better to look at the code of these projects instead of looking videos because existing videos can't demonstrate good sample of architecture, just a simple usage of functionality.
About server controls, you may use them if they can be used without 'runat="server"', like PlaceHolder. And you may create them too, but you shouldn't load any data in them directly. If you don't want to copy-paste html you should review your code and you should refactor it. Every duplicated code should be moved to MasterPages of UserControls (ascx ones).
And once more, please spend some time to look at these samples. You'll save your nerves and time in the future when you'll need to update the app or fix something. At the first look they can be hard to understand but this is only at the first look.
Hope this helps.
#lopkiju, I think that the MVC pattern would serve you much better than your current WebForms solution if you want that much control over the output HTML.
You can use Web Forms this way as you already do, but it is not designed to be used this way, so it will be a pain.
More detail
In my opinion, read some articles about the Separation of Concerns (also known as SoC) principle. If you apply it correctly, it can save you many-many headaches when you'll debug your app, and also for those people who you work with (eg. those who may have to read or modify your source code).
My other tip for you is this:
You are right that you shouldn't do things like <% while (dataReader.Read()) %> in your View code. But perhaps there are better ways to make it more elegant than your current way.
I think you should consider using some sort of ORM for these purposes. (LINQ to SQL, or even NHibernate.) If you get it, it will be much simpler. So much that you may not want to use DataReaders directly again. :-)
What I recommend for you
Simply, read the NerdDinner tutorial, and build the samle app by yourself step-by-step.
After that, try to build a similar app that serves a different purpose by yourself while applying the same rules and design that you applied to the tutorial.
I'm pretty sure you have the expertise to do it, and after actually doing something with it, you can pretty much get the feel of it.
The tutorial also explains and includes the principles I mentioned above, which will be very much use to you.
If you want the ASP.NET MVC path, you can set up controls as ASCX and they will simply be tags filled by the controller. It may not be old school enough for you, however.
You can create your full UI in code behind, if you so desire. This can include creating the HTML in routines.
But, I would recommend, if you are sticking with ASP.NET, reconsidering the bind model over the DataReader.Read() and output + loop. It is not only old style, it is highly inefficient and hard to maintain.
ASP.NET MVC does create a much looser ASPX, as it is just a view. And there is a much greater separation of code and UI. But it will not fit with the old school model either.
Have you considered using micro-templates? Dave Ward has a good example of of a client side data repeater that is uses micro-templates for layout after making a call to a page method. This sounds like this is more in the spirit of what you are trying to accomplish and can still be integrated nicely with WebForms.
The side effect will be that you will not rely on passing around HTML and can isolate your presentation from your logic.

ASP.NET MVC Views - Can I use code-behind

I am new to MVC and I notice that the view pages can look pretty nasty with all the intermixed script tags. Does it make sense to generate the HTML in a method in the view code-behind and then just insert the string result of the method as a single bit of script?
For example: <div><%= GenerateTonsOfHTMLFromSomeIEnumerable() %></div>
Is this contrary to the MVC philosophy? Dumb for some other reason, like performance? Does it have any merit?
It's a matter of practice.
Here's an interesting read.
Codebehind files are evil
Codebehind files are not evil
Also there's an interesting article by "Rob Conery"
Inline Scripting and Code behind
So, the choice is yours. It depends on your application architecuture, how you want to structure it, blah-blah...
I guess the advantage with views without codebehind is that is is much easier to switch to different viewengine which doesn't support codebehind.
Though there will be some amount of work, but still it will be much seamless.
OK, chalk up another for the learning curve. I think I might have found the answer to my own question...
ASP MVC lets you install your own custom view engines which you can use (instead of the default ASP.NET view engine). So you can control the html generation. Once you know what to search for, its easy :)
Here's a good place to get started: Custom View Engine Example
#Rajesh - Thanks for the great links!
I wouldn't. You just need to forget about the codebehind file, seriously. In fact in MVC Framework RC1 by default there is no codebehind file for your views. Whatever c# processing you want to go on to render your view you can do it inline with your HTML. If you are thinking about doing some data processing, do yourself a favor and put it in the controller.
This is a paradigm shift, its best to just break your old habits now.
You can use code behind as well. It is only a matter of style preference.

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.

Code behind in ASP.NET MVC

What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?
Here's my list of reasons why code-behind can be useful taken from my own post. I'm sure there are many more.
Databinding legacy ASP.NET controls - if an alternative is not available or a temporary solution is needed.
View logic that requires recursion to create some kind of nested or hierarchical HTML.
View logic that uses temporary variables. I refuse to define local variables in my tag soup! I'd want them as properties on the view class at the very least.
Logic that is specific only to one view or model and does not belong to an HtmlHelper. As a side note I don't think an HtmlHelper should know about any 'Model' classes. Its fine if it knows about the classes defined inside a model (such as IEnumerable, but I dont think for instance you should ever have an HtmlHelper that takes a ProductModel.
HtmlHelper methods end up becoming visible from ALL your views when you type Html+dot and i really want to minimize this list as much as possible.
What if I want to write code that uses HtmlGenericControl and other classes in that namespace to generate my HTML in an object oriented way (or I have existing code that does that that I want to port).
What if I'm planning on using a different view engine in future. I might want to keep some of the logic aside from the tag soup to make it easier to reuse later.
What if I want to be able to rename my Model classes and have it automatically refactor my view without having to go to the view.aspx and change the class name.
What if I'm coordinating with an HTML designer who I don't trust to not mess up the 'tag soup' and want to write anythin beyond very basic looping in the .aspx.cs file.
If you want to sort the data based upon the view's default sort option. I really dont think the controller should be sorting data for you if you have multiple sorting options accessible only from the view.
You actually want to debug the view logic in code that actuallky looks like .cs and not HTML.
You want to write code that may be factored out later and reused elsewhere - you're just not sure yet.
You want to prototype what may become a new HtmlHelper but you haven't yet decided whether its generic enough or not to warrant creating an HtmlHelper. (basically same as previous point)
You want to create a helper method to render a partial view, but need to create a model for it by plucking data out of the main page's view and creating a model for the partial control which is based on the current loop iteration.
You believe that programming complex logic IN A SINGLE FUNCTION is an out of date and unmaintainable practice.
You did it before RC1 and didn't run into any problems !!
Yes! Some views should not need codebehind at all.
Yes! It sucks to get a stupid .designer file created in addition to .cs file.
Yes! Its kind of annoying to get those little + signs next to each view.
BUT - It's really not that hard to NOT put data access logic in the code-behind.
They are most certainly NOT evil.
Ultimately, the question you ask yourself is this:
Does this code A) Process, store, retrieve, perform operations on or analyze the data, or B) Help to display the data?
If the answer is A, it belongs in your controller. If the answer is B, then it belongs in the view.
If B, it ultimately becomes a question of style. If you have some rather long conditional operations for trying to figure out if you display something to the user, then you might hide those conditional operations in the code behind in a Property. Otherwise, it seems like most people drop the code in-line to the front end using the <% %> and <%= %> tags.
Originally, I put all my display logic inside the <% %> tags. But recently I've taken to putting anything messy (such as a lengthy conditional) in my code behind to keep my XHML clean. The trick here is discipline - it's all too tempting to start writing business logic in the code behind, which is exactly what you should not be doing in MVC.
If you're trying to move from traditional ASP.NET to ASP.NET MVC, you might aviod the code behinds until you have a feel for the practices (though it still doesn't stop you from putting business logic inside the <% %>.
There isn't a purpose. Just don't use it except for setting the model
ViewPage<Model>
See this blogpost for more info.
At this Blogpost is a working example of removing the code behind.
The only problem I'm stuck with is that it is not able to set namespaces on the class.
The codebehind provides some of the strong typing as well as the intellisense support that you get in the view. If you don't care about any of these two features, you can remove it.
For example, I typically use the NVelocity ViewEngine because it's clean and pretty straight forward.
This is a great question. Doesn't MVC exist in the ASP.NET environment, without using the specific MVC pattern.
View = aspx
Controller = aspx.cs (codebehind)
Model = POCO (Plain Old C#/VB/.NET objects)
I'm wondering why the added functionality of MVC framework is helpful. I worked significantly with Java nd MVC and Java Struts several years ago (2001), and found the concepts in MVC to be a solution for the Internet Application organization and development problems at that time, but then found that the codebehind simplified the controller concept and was quicker to develop and communicate to others. I am sure others disagree with me, and I am open to other ideas. The biggest value I see to MVC is the front controller pattern for Internet development, single entry source for Internet Application. But, on the other hand, that pattern is fairly simple to implement with current ASP.NET technologies. I have heard others say that Unit Testing is the reasoning. I can understand that also, we used JUnit with our MVC framework in 2001; but I have not been convinced that it simplifies testing to use te MVC framework.
Thanks for reading!

Resources