Using Code-Behind with ASP.NET MVC Views - asp.net-mvc

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.

Related

What is difference between View and Page in Asp.net core 2?

I am new in Asp.net core 2. One of the new things in Asp.net core 2 are pages.
But I can't figure it out
What is difference between page and view?
What are the benefits of pages versus views?
In what cases should the page be used?
Can I use both at the same time?
Really, your question is what's the difference between a Razor Page and traditional MVC. Both utilize Razor views. A Razor Page is self-contained (sort of). It has a code-behind like a Web Form, so technically you'd have a cshtml and a cshtml.cs file, the latter of which would act as both your controller and your model. Whereas, with traditional MVC, you'd have separate FooController, FooViewModel, and Foo.cshtml. Aside from some slight functional differences (such as having to use convention-based "actions" like OnGetAsync, OnPostAsync, etc. with Razor Pages) that's pretty much it.
The chief benefit to Razor Pages, as I see it, is its self-contained nature. All the code regarding a particular piece of functionality is essentially all in one place. However, the downside to this is that it can make code reuse difficult or at least not as intuitive in some places. Personally, I think the clear division of responsibilities offered by MVC is the more ideal approach and its also less "magical". One of the marketing touchpoints of Razor Pages is that it's stupidly easy. That may be true, but it owes its "ease" to abstracting away things web developers should actually be cognizant of, and that can be dangerous. If you don't actually understand how something works, you won't know if you're doing things right.
I'm biased, but to honestly answer "When should Razor Pages be used?", I would say never. I don't like the mixing of responsibilities, all the "magic", etc. Since they were introduced the number of ASP.NET Core questions here have skyrocketed and the majority of the Razor Pages questions are about things that are either obvious or at least more intuitive with MVC. That said, if you are going to use them, they make the most sense on CRUD type stuff - things that don't have a lot of functionality and are fairly straight-forward and/or repetitive.
Finally, yes you can freely mix and match Razor Pages and MVC. However, it should be noted because it's not obvious to everyone: Razor Pages only work as Razor Pages when used as Razor Pages. In other words, if you create a view with a code-behind (a Razor Page) and then use that view as a return from an MVC action, a partial, etc., the code-behind isn't actually utilized, just the "view" portion. Actually, to be more accurate, it is "used" but only to provide the model for the view in a general sense, since the view uses the Page in the code-behind as its model. However, this won't actually be "active", in the sense that page actions won't be hit, things likely won't get initialized properly, etc.

Is MVC Framework ill-equipped for rich page design?

Just to prefix this question, I've decided to take a look at moving our works old legacy systems (40+ programs from vb6, vba, vb.net to c#.net) into two separate systems using the same DAL (barcoding terminals and one web based system) as I spend most my day fixing crummy or non existant business logic in 15 year old vba programs. I've recently built an entity framework model complete with fluent validation and couldn't be happier with it after using it for a bit.
The small team is familiar with webforms (but not very) but the last few days I've explored MVC Razor. I was loving MVC Framework until I tried to start trying to add more functions onto the same page and then it seemed arbitrarily hard to replicate our a recent system I put in a webform. Before, I would eager load a customer and all it's child entities and then bind that to single page for the customer so they could access everything (which is what they wanted), it works okay and isn't slow. From this single page I could edit all their account details/contacts/emails/phones/jobs.
All the examples I've done and seen in MVC handle a single update, a single edit etc but surely you can't separate out every single action into a new view/page? I can pass a rich model through to the view in MVC, but then its a pain trying to update all the different child entities.
This is probably the exact design that MVC wasn't designed for maybe, which is okay, I'm willing to adapt it if MVC will be a better platform going forward, but how are you meant to handle adding this complexity in? Some methods I've seen:
Lots of partial views? passing child info to them (or the id and lazy loading it)?
I've seen methods that wrap multiple <forms> around everything and handle actions that way.
Separate pretty much every task out
If the solution is more lightweight and easier to maintain I'll go research whatever I need to I just wanted at an earlier stage to see if I'm wasting my time. Any pointers to the correct questions I should be asking would be greatly appreciated.
ASP.NET MVC is neither more or less better equipped to deal with complex pages than any other technology out there.
Certainly, MVC requires more low-level work than a Web Forms app, with no direct binding support, but in most cases this is a good thing and provides much more flexibility in how your page is rendered.
One of the whole ideas of MVC is to give you more control over things, but that control leads to requiring more knowledge and more effort on your part in most non-trivial cases. MVC provides a number of tooling functions to speed up trivial work (like creating standard table based CRUD) but when you have complex models, you will have to do much of the work yourself.
This is not that MVC is "ill suited" for it, but just that control and flexibility has a trade off with more responsibility on your part.
In your case, you simply create a view model with all the fields you want. Then, you create your form to edit those fields. In your controller, you will need to unflatten that view model and create or update the necessary records in the database. It's not difficult, but it's more work than WebForms databinding.
You could look into more advanced tools (commercial) for MVC, such as Telerik's tools, which have developed more of a databinding like interface, but MVC is not a drag-n-drop technology, and requires you to hook things up and write the various logic for what is done.
If you need drag-n-drop, databound functionality, then no.. MVC is not the correct technology. But then WebForms requires you to accept many compromises as well, and ties your hands in many ways.
You could use partial views, however I seldom use them. I prefer to instead use Editor/DisplayTemplates as these take care of naming your form fields correctly, even for collections and complex objects. PartialViews tend to have lots of gotchas if you aren't careful. I pretty much only use them as fancy includes, or when using Ajax.
I'm not sure what you meay by "wrap multiple <forms> around everything`. You cannot nest forms in HTML, it's not legal. If you mean place a form around each row of a table, that isn't valid html either in most cases (it's not legal to put a form in a between the table and the tr).
It would help if you had a specific problem that you could ask about, vague objections don't help us solve your issue.
You can accomplish anything in MVC that you can in WebForms. The difference is MVC will usually require you to write more code as it doesn't really offer you any "controls" to drop on your page.
In WebForms, it's easy to create a master/detail view with a GridView, FormView and then wrap everything in an UpdatePanel for automagical AJAX support.
In MVC, while you do have helpers like the WebGrid and AjaxHelpers extension methods, creating views and/or pages requires more understanding of how things work to get the desired functionality. When I start a new MVC project, here's what I include:
Backbone.js - client-side "ORM" that performs CRUD operations
against RESTful* APIs
Knockout.js - client-side view models and
real-time data-binding for your views
Knockback.js - wraps
Backbone models in Knockout view models
Using these three frameworks, you can quickly create powerful single-page apps using MVC and WebAPI.

main purpose of using mvc

Ive been doing a bit of research / reading into mvc recently and was just wondering what the main purpose is.
is it as some people say to seperate the logic from the html
or to create clean url's
i could be missing the point completely, but asp.net forms really seperates the logic from the html and if you just want clean url's why not use a mod_rewrite rule?
MVC is a software engineering concept which is used more widely than just in ASP.net.
In a nutshell it encourages strong separation of:
business logic (the Model) the code which does all the brute force work behind the scenes; dealing with the database, performing large calculations; and
user interface logic (the View) the code which presents information to your users in a pretty way.
The C is for Controller - the ligaments that bind the bones of the model and the muscles of the views and allow them to communicate with each other cleanly.
You are correct that 'normal' ASP.net uses code-behind files so that page markup is kept separate from the code that generates that markup (in contrast to languages like PHP where code is embedded directly amongst HTML), but MVC ASP.net encourages even more separation in the ways I described above.
Take a look at this tutorial for a more detailed discussion of the pattern. Also take a look at this SO question
The MVC pattern has nothing to do with rewriting URLs. ASP.net MVC might make this easier but that is not by any means it's main purpose.
Testability is a big benefit of using ASP.NET MVC. It is non-trivial to write unit tests for ASP.NET winforms. It is much easier to unit tests for Controllers.
If you are doing MVC correctly, your views should be very light, and a lot of your logic is implemented in the Controllers.
Let me compare the two for you:
Asp.net web forms
They matured the old ASP technology that was much more like PHP. Code and presentation were piled up in the same file. Asp.net web forms upgraded this model by providing a mechanism of separating the two. But they built on top of the good things that windows application developers had. The drag drop interface creation with control events just like they exist in a windows application. Event thought code was separate from HTML, they were not separated. You still reference a lot of view controls in your codebehind, hence they're still very much bound to eachother.
Therefore it was rather easy to start developing on Asp.net web forms. But non savvy developers soon got to a bottleneck they didn't know existed (like slow postbacks due to huge view state etc.). Technology used some tricks to make this work. But on a serious large scale application this became quite a problem. Developers had to mingle their code to make it work with Asp.net web forms framework. Their complex forms had complex codebehinds with hard maintainable code with complex state.
The good (as well the bad) thing were at that time rich server controls. Nowadays with web 2.0 they don't seem rich anymore since they don't actually support client side functionality as much as they should. So Microsoft decided to also cram in something else. Update panels. That made partial rendering (and Ajax) possible with almost a flick of a finger. But it came with a cost. Everyone that used (uses) it soon realised it's not a viable solution that a professional application could implement.
Asp.net MVC
Now we have a new technology that doesn't have much in common with Asp.net web forms except for its first part of the name. MVC framework actually does separate code from user interface (view). Controller actions (code that executes on any HTTP request) is kept small and doesn't do anything with visualisation (it doesn't bind data to certain controls etc.). Controller action barely prepares data for the view to either consume or not. It's up to the view. Controller code doesn't in any way shape or form reference any view controls or anything. They're actually separate in MVC.
Views on the other hand just display and provide data. They can be partially or fully rendered. They support Ajax functionality to the point that everyone would like to use. Actually everything is separated into basic little things. Divide et impera (divide and conquer) seems to be the save-line here.
There's not hidden functionality. No flirting with windows development. It pure request response framework. Developer has the ability to 100% control the visual aspect of their app. But for the cost of not having rich controls out of the box. Those may be provided by the community or some developers prefer to create per purpose controls that serve the process much better.
Which one is better then?
Both have their pros and cons. But if you decide to build a semi complex, modern and maintainable application I'd suggest you give MVC a go.
But if all you need to do is a 15 screens application (without any particular interface requirements) it would be much faster to create it using Asp.net web forms.
MVC is a design pattern. Its purpose is to separate business logic and presentation details.
ASP.Net MVC is a mechanism to create web applications using ASP.Net and the MVC pattern.
One of the features of ASP.NET MVC is the ability to use SEO friendly URLs to provide commands to the controller part.
You can do as you have stated but ASP.Net have provided you a mechanism to do this easier.
The way ASP.Net Webforms was designed is that it made it easy for you drag controls on to the web form and code the logic underneath. ASP.Net MVC is designed so you separate your concerns easier.
The URL part of the ASP.NET MVC framework is just a modern phenomena to produce search engine friendly urls. They've infact been around long before the Microsoft team decided to add them to the framework (which required IIS7 before it could be done with no IIS extension).
The greatest pros in my view come from being able to test more easily, and separating off the parts of your application more cleanly. The whole ActionResult architecture of the ASP.NET MVC framework makes it very easy to switch from AJAX to plain out POSTs.
Delphi 5 use to employ the MVC model for its ISAPI extensions, 10 years ago.
MVC is not just an ASP.net thing, it is a design pattern that was widely accepted before it was created within the .NET framework, the thing about MVC is the separation of data from presentation(user interaction) from the business layer. It was just a way for Microsoft to offer that type of design pattern under the .NET framework
Although guys before me already give enough answers to the queston of purpose of ASP.NET MVC there is one thing I would like to add.
The ASP.NET Web Forms tried to abstract html and web from web development. That approach lead to the lacks in performances and usage of rich javascript frameworks.It was possible to create web application without actual knowledge of the web.
And to answer to you initial question, the purpose of ASP.NET MVC, I'll quote Dino Esposito:
With ASP.NET MVC, you rediscover the good old taste of the Web—stateless behavior, full control over every single bit of HTML, total script and CSS freedom.
MVC existed long before people tried to use it in HTML pages. The main reason for MVC is to get a grip on the logic to drive your application. MVC allows you to clearly separate things that should be separate: The model, code which converts the model value for the display and the code which controls the model.
So this is not related to HTML or URLs in any way. It's just that MVC makes it really simple to have clean HTML and simple URLs.

Are we moving towards classic ASP using MVC framework in .Net 3.5?

Looking at MVC framework, it seems we require more of classic ASP knowledge then ASP.NET postbacks and Viewstates. Are we moving backwards to complex UI + code logic in the actual frontend HTML markup?
We're moving back to not trying to abstract away fundamental concepts like HTML and HTTP Requests. On the UI end, that translates into the Views being more tightly integrated with the output, which isn't a bad thing. the classic ASP model translated into having everything tightly integrated with the output, which is a bad thing.
One could argue that the MVC paradigm is a step backward if you consider the ASP.NET paradigm a step forward, I guess. Personally I always thought it was much easier to write clean separated code in classic ASP, rather than .NET where display output text usually got mashed into code blocks where it was impossible to access with a standard HTML editor. I always thought the ASP.NET architecture was more about pushing .NET than improving the overall structure of we application, so in that sense MVC is a step forward.
This is funny that you mention this ... I was having the same conversation with a co-worker today.
Is it a step moving backwards? I don't think so ... while in classic asp you had a some complex logic in the UI, from what I can see with MVC, the complex logic should still be in your business objects, and any complex interaction with the object should be done via the Controller.
The goal, again, from what I can see, is to keep the UI trim and fit when it comes to actual business logic. Any additional bloat would be caused by making the UI more user friendly, with the likes of AJAX and JQuery.
This is just my initial observation regarding MVC. It is a very cool technology, especially with how it sits on top of REST, makes it very easy to work with from other technologies.
I'm looking forward to trying it out in a couple of future projects!
If you are seeing complex code logic in the View relative to the Models and Controllers, than perhaps you are approaching it the wrong way.
In the pure sense, you should be able to switch out the view (XML instead of HTML let's say) with minimal work. That could only happen if the data logic is contained in the models and the business logic ins contain in the controllers.
So, if you were displaying a shopping cart, the view might only have code that writes out the product quantities and totals. The model class(es) would hold the product data and the controller would do all the processing such as adding products and checking out.
The entire point of MVC is for separation of code. Models should contain all of your business logic, the View should just handle the output to the user, and the Controller should glue those two pieces together.

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