ASP.NET MVC Views - Can I use code-behind - asp.net-mvc

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.

Related

Asp.NET MVC view engines, why they don't support "View designer" now?

With the asp.net MVC, we see a lot different view engines, like Razor, spark, webform etc.
I thought the idea of MVC is separating of data and view, I assume view part should be something that allows a designer to do some work, even after it is created by a developer. But I see now most if not all view engines introduce new syntax, not stick with html. The old web form, you can use "view designer" to see how a page looks like even with some code blocks, designer could at least move blocks and html elements around, but now with engine like Razor, you cannot even view a page in designer mode. So I don't quite get what is the point?
This came to me when I tried to search for a server side templating that allows end user do some changes on the page. I perfer something stick to pure HTML, maybe Spark is the one, but I am not sure. Please someone can give me some idea.
Thanks
Views are meant for that. It will not static design. Markup will be generated on fly.
If you take razor as an example, you will have the combination of c# and html as code in view page. So, as you may be able to understand now, you cannot see the actual design until the c# and html execution goes hand-in-hand.
Hope it clarifies a little!

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

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.

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.

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.

Resources