ASP.NET MVC: Am I doing it right? - asp.net-mvc

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.

Related

Changing the View Engine in Asp.NET MVC

I am trying to learn ASP.NET MVC by porting my current app written in ASP.NET Webforms to MVC. For starters, I am planning to use the Default View Engine (WebFormsViewEngine) as most tutorials/examples and the book I have use that as the default.
However, I know for sure that I do not want to use WebformViewEngine in the future and once I have a grasp of MVC, I would like to switch to a different ViewEngine (Spark seems to be interesting)
Would this be a simple change or would it take a lot of effort in terms of coding new views? What I basically want to know is which would involve more effort? Learning an alternate ViewEngine now or switching later?
OK - firstly you've got a decent sized investment in WebForms I'm assuming, and by virtue of that, you'll have a fair amount of user controls on existing forms etc. I'm sure you already know that this in itself is going to be the most work in the process, and has nothing to do with which view engine you choose because even the WebForms MVC view engine doesn't support user controls directly. This part of the work will still need to be done regardless...
Secondly, you probably are looking for a view engine that can take most of your other view built in logic and code (i.e not user controls), and by that I mean the stuff between the bee-stings ( <%= blah %> ).
Obviously the WebForms view engine does support this same syntax, but you also say that you specifically don't want to use the default WebForms view engine. Well you'll be happy to know that Spark also supports the <%= blah %> syntax, and this has been done specifically to support migrations like this.
Your best bet before deciding would be to watch this recent video here, and see how Louis goes through the simple WebForms-based MVC solution and it keeps running correctly even though the code still contains <%= blah %> syntax.
This support makes it much easier to transition and when you're ready you can then start moving your code to the more recommended way of using ${blah} syntax instead. But this can be done at your own pace whilst the overall functionality still works.
Hope that helps,
All the best,
Rob G
Looks like you can have a mixed bag of view engines in your application... link
Also check out this post from Phil Haack that shows using partials using different view engines to render on the same page.
This would allow you to simply switch over to the new syntax and not need to rewrite all of your existing views.
It should be as simple as calling
SparkEngineStarter.RegisterViewEngine(ViewEngines.Engines);
SparkEngineStarter should be a class in the Mvc part of Spark.
The documentation of spark is actually pretty good. Check out the section on getting it to run in ASP.NET MVC

Using Code-Behind with ASP.NET MVC Views

Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.
Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.
I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.
Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).
Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.
I used code-behind extensively on my first ASP.NET MVC (Preview 3!) project - primarily for doing stuff like casting ViewData["foo"] into strongly-typed data objects, gathering view data into IEnumerables so I could loop across it, that kind of thing.
With the introduction of strongly-typed views, and pragmatic use of the (horrifically-named) Model-View-ViewModel pattern, I haven't missed code-behind at all since it was removed from the project framework just before the final release.
I now strongly feel that whatever processing you're doing in your view's code-behind, you are far better off modelling the result of that processing in your ViewModel, allowing the controller to perform the actual processing, and keep the view as simple and lightweight as you can. That'll let you test the processing logic, it makes the views easier to modify, and creates - I think - a much more elegant separation between transforming your data for display, and actually displaying it.
Yes the codebehind has long been the secret hiding place of business logic which as we all know should not be at the View level.
Code behind has been removed to stop naughty developers from being tempted.
I would recommend avoiding the codebehind in an MVC app at all costs. Using the code behind negates some of the values you get by using the MVC Framework such as separation of concerns, etc. You want to have your data access, business rules, type conversion and that sort of thing applied in the Model. If you find you need to convert your data types like Dylan mentioned, you may want to make ViewModels. The ViewModel would basically be the data from the actual Model you would like to display, in the format you wish to display it in.
Its probably best to avoid putting anything in the code behind when using MVC.
I would be interested to hear which part was being debated about, to go in the codebehind?
If you new to Asp.Net MVC, I really recommend spending some time going through the Nerd dinner example. There's a free EBook and source available here http://nerddinner.codeplex.com/.
Creating the simple demo from scratch is a great way to learn.
After doing this, it may shed some light on where the code you have in the codebehind, could alternatively go.
Note: If you do follow the EBook, grab the latest site.css file from codeplex, otherwise the virtual earth maps won't be aligned properly.
HTH
Ralph
It should be noted that "Code Behind" is a feature of the Web Forms view engine. It really has nothing to do with ASP.NET MVC itself.
For example, the Razor view engine in MVC3 does not even support it.
I would answer your question this way: If you cannot switch view engines without rewriting your controllers (or even your models) then you are not using the MVC pattern correctly.
Probably most of what you are doing in the .aspx.cs file should really be done before the model (or View Model) gets passed to the view. That said, in projects that I have migrated from ASP.NET Web Forms to ASP.NET MVC, I left a lot of the Code Behind in place. For example, I find it cleaner and more pleasing to use a Repeater control than to try to use a 'for' loop in Web Forms. I am still just iterating over View Model data after all. So why not? Separation of concerns is preserved (perhaps to a greater degree in fact).
I mean, why should "best practice" for Web Forms suddenly be the wrong way to do a Web Forms View? As a simple example, consider a Repeater that assigns a different CSS class to every second row of a table. Why should my controller (or even my model) care? Trying to put this kind of logic inline in Web Forms quickly devolves into tag soup and complete spaghetti. Now imagine something more complicated.
I have left Master pages in place that build the menus in the code behind. Again, all data comes from the View Model. I do not see why using GridView or other controls in this way should be a problem either.
I usually disabled ViewState in Web Forms anyway and did the data binding in "Init". Still, there would often be a small ViewState that I could not get rid of. I put some code in "Render" that moves this to after the form (it defaults to before). When moving to MVC, I sometimes left this code in. So, I have ASP.MVC sites that do indeed use Code Behind. I am just careful that it code that is specific to the view.
On new projects, I generally have found less of a need for Code Behind on most pages. Thankfully, view engines like Razor have made mixing code and mark-up in-line a lot less painful to write, read, and maintain.

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.

Which way do you prefer to create your forms in 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.

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