What Is ASP.Net MVC? - asp.net-mvc

When I first heard about StackOverflow, and heard that it was being built in ASP.Net MVC, I was a little confused. I thought ASP.Net was always an example of an MVC architecture. You have the .aspx page that provides the view, the .aspx.vb page that provides the controller, and you can create another class to be the model. The process for using MVC in ASP.Net is described in this Microsoft article.
So my question is. What Does ASP.Net MVC provide that you wouldn't be able to do with regular ASP.Net (even as far back as ASP.Net 1.1)? It is just fancy URLs? Is it just for bragging rights for MS to be able to compare themselves with new technologies like Ruby On Rails, and say, "We can do that too"? Is there something more that ASP.Net MVC actually provides, rather than a couple extra templates in the File->New menu?
I'm probably sounding really skeptical and negative right now, so I'll just stop. But I really want to know what ASP.Net MVC actually provides. Also, if anybody can tell me why it's Model-View-Controller and not in order of the layers of View-Controller-Model or Model-Control-View depending on whether you are going top to bottom, or vice versa, I'd really appreciate that too.
EDIT
Also, it's probably worth pointing out that I've never really cared for the web forms (AKA server controls) model either. I've only used it minimally, and never on the job.

.aspx doesn't fulfill the MVC pattern because the aspx page (the 'view') is called before the code behind (the 'controller').
This means that the controller has a 'hard dependency' on the view, which is very much against MVC principles.
One of the core benefits of MVC is that it allows you to test your controller (which contains a lot of logic) without instantiating a real view. You simply can't do this in the .aspx world.
Testing the controller all by itself is much faster than having to instantiate an entire asp.net pipeline (application, request, response, view state, session state etc).

Scott Guthrie explained it in this post "ASP.NET MVC Framework"
It enables clean separation of concerns, testability, and TDD by
default. All core contracts within
the MVC framework are interface based
and easily mockable (it includes
interface based
IHttpRequest/IHttpResponse
intrinsics). You can unit test the
application without having to run the
Controllers within an ASP.NET process
(making unit testing fast). You can
use any unit testing framework you
want to-do this testing (including
NUnit, MBUnit, MS Test, etc).
It is highly extensible and pluggable. Everything in the MVC
framework is designed so that it can
be easily replaced/customized (for
example: you can optionally plug-in
your own view engine, routing policy,
parameter serialization, etc). It
also supports using existing
dependency injection and IOC container
models (Windsor, Spring.Net,
NHibernate, etc).
It includes a very powerful URL mapping component that enables you to
build applications with clean URLs.
URLs do not need to have extensions
within them, and are designed to
easily support SEO and REST-friendly
naming patterns. For example, I could
easily map the /products/edit/4 URL to
the "Edit" action of the
ProductsController class in my project
above, or map the
/Blogs/scottgu/10-10-2007/SomeTopic/
URL to a "DisplayPost" action of a
BlogEngineController class.
The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and
.Master markup files as "view
templates" (meaning you can easily use
existing ASP.NET features like nested
master pages, <%= %> snippets,
declarative server controls,
templates, data-binding, localization,
etc). It does not, however, use the
existing post-back model for
interactions back to the server.
Instead, you'll route all end-user
interactions to a Controller class
instead - which helps ensure clean
separation of concerns and testability
(it also means no viewstate or page
lifecycle with MVC based views).
The ASP.NET MVC framework fully supports existing ASP.NET features
like forms/windows authentication, URL
authorization, membership/roles,
output and data caching,
session/profile state management,
health monitoring, configuration
system, the provider architecture,
etc.

Primarily, it makes it very easy to create testable websites with well defined separations of responsibility. Its also much easier to create valid XHTML UIs using the new MVC framework.
I've used the 2nd CTP (I think they're on five now) to start work on a website and, having created a few web applications before, I have to say its hundreds of times better than using the server control model.
Server controls are fine when you don't know what you're doing. As you start to learn about how web applications should function, you start fighting them. Eventually, you have to write your own to get past the shortcomings of current controls. Its at this point where the MVC starts to shine. And that's not even considering the testability of your website...

No more auto-generated html IDs!!! Anyone doing any sort of javascript appreciates this fact.

ASP.Net with it's code behind is almost MVC - but not - the one big thing that makes it not is that the codebehinds are tied directly to the aspx's - which is a big component of MVC. If you are thinking of the codebehinds as the controller - the should be completely decoupled from the view. The new .NET MVC rounds this out - and brings a complete MVC framework. Though there are existing ones for .NET already (see Spring.NET).

I looked through a couple simple examples such as this one. I can kind of see the difference. However, I don't really see how MVC uncouples the view from the controller. The view still references stuff that's in the controller. I do see how it makes it much easier to test, and that at least in MVC the controller doesn't have any knowledge of the view. And you wouldn't have to process the view to call methods in the controller. I can see that's quite a leap, even though at first glance it may not seem like much.
I do agree with #Will about fighting server controls. I've never worked in a situation where they were actually used, but many people I know who have, have run into quite a few limitations with them.

Article about ASP.net MVC Vs ASP.net Web form
http://weblogs.asp.net/shijuvarghese/archive/2008/07/09/asp-net-mvc-vs-asp-net-web-form.aspx

Related

ASP.NET MVC and Angular JS tipping point

I want to create a largish ASP.NET MVC Web application. On some pages I would like to utilise AngularJS.
This app will not be a SPA.
At what point does this become a problem? For example at what point does running effectively two MVC paradigms become a headache?
Or is it a case of as long as you have clear delineation between what's using ASP.NET MVC (standard action methods etc) and what's using Angular JS then the two run side by side ok without giving you massive code organisation/maintainability headaches?
Cheers for any wisdom.
I'd love John Papas opinion!
Andrew
Since you are only asking for opinions, I will be happy to share my experience. The two do mix very well, and I think in most cases (at least most of my own development) the .NET side becomes very light weight.
Your .NET Web API Controller becomes a simple call to the Data Layer to populate a model or List(Of T) models. This gets returned as JSON to the Angular service.
From there, Angular takes over all of the logic until you need to perform another CRUD operation. Manipulating, validating, etc. all happens client-side in either the model (for me the Angular service acts as the model in MVVM) or the angular controller (which is really a ViewModel).
It's best if you let your model (Angular service) handle as much business logic as possible and restrict the Angular controller to responding to clicks, input controls, etc.
To sum up, let your .NET server side be very light. Just transport data back and forth to the Data Layer. Let Angular do the heavy lifting. You definitely do not need to be building a SPA to see the wonderful benefits of a JS data binding library, of which Angular is arguably the best of breed.
An excellent blog post that contains [ details of what I've discussed here ].
Good luck!
I use ASP.NET MVC alongside AngularJS for a fairly large in-house application. We don't really use many features of ASP.NET MVC beyond the basic page template and script bundling - so everything from the client-side is controlled by AngularJS and client-side routing - except for some distinctions we've made between 'modules' of the app where we wanted a different ng-app for each, along with different script dependencies.
If you're looking to take advantage of AngularJS on a page-by-page basis then I think you have no problem at all. As long as you reference the scripts (both core AngularJS scripts, and your AngularJS scripts for modules, controllers, etc.) correctly then you can just begin decorating elements with ng-app, ng-controller, etc. and it will just work. You could insert the relevant AngularJS scripts for relevant .cshtml pages using a #section declaration.
It will only be more complicated if you need a mix of server-side and client-side routing. Then it will be a case of carefully constructing ASP.NET MVC routes to deliver the SPA functionality where needed.

MVC 4 / Razor in layman's terms

I'm sorry if this is a stupid or obvious question, but I've spent the better part of a week researching, and I really can't find any resources that explain what MVC 4 and Razor are, and what they are intended to do in web development. I'm not necessarily asking for a really detailed description, even a link to a website or the name of a book that doesn't explain MVC 4 by referencing other technologies that I have also never used. I've looked through articles, articles and tutorials on everything from MSDN to graduate papers and I just don't get it.
I know what MVC the design pattern is, but one of the main things I can't get a straight answer to is what the difference is between MVC the pattern and MVC 4 the framework. As a web developer, will I ever have to change or make use of the frameworks, or is it something that is supposed to "stay out of your way" (to quote another SO post.) Is it something that gets generated by VS and I will never have to touch?
Again, I'm sorry if this is obvious, maybe I'm trying to make this more complicated than it actually is. All I have been looking for is a straight forward answer with concrete examples that don't contradict or complicate it any further.
Please...I'm at my wits end here. My last question was apparently too vague and got voted down and closed, so I tried to be more specific, but part of my problem is what are the right questions to ask.If there is anything that can say to clarify,please tell me.
I certainly don't want to discourage you any more than you appear to be at the moment, but in my opinion, if you can't make head or tail of the huge amount of material that already exists on MVC, then perhaps you are just not ready for it yet. That's OK - in fact Microsoft recognise that MVC is complicated, which is why they introduced the ASP.NET Web Pages framework (which is what gave birth to Razor syntax).
My advice would be to follow the link and download WebMatrix. Then follow some of the Web Pages tutorials. That way you can get your head around Razor without worrying too much about MVC for the time being.
Incidentally, ASP.NET MVC is a web development framework that enables you to build web applications based on the MVC pattern. You need to understand how MVC works in order to make use of the framework. You need to understand what Models are, what Views are and the role that Controllers play in the whole thing.
The framework itself is not an example of MVC.
Razor is a templating syntax that allows you to intermix C# (or VB) with HTML to output dynamic content in a View in MVC or a page in the Web Pages framework.
I know it may seem confusing, but it seems to me that you are over complicating things.
The simple matter is that MVC is a design pattern. That is, it's an abstract thing.. a philosophy of sorts. It's not a concrete thing. A design pattern simply gives you a description of how the pattern is supposed to work, and while it may give you a sample implementation, in general it leaves that implementation up to you.
ASP.NET MVC (whichever version) is a specific application framework that uses the MVC pattern as its basis. In other words, it's a concrete implementation of the MVC design pattern.
In fact, the ASP.NET MVC implementation isn't even a "true" implementation of the MVC design pattern, as certain compromises are necessary to make it work in a web based model. So it's really more "MVC design pattern inspired".
You're overthinking things. Just accept that ASP.NET MVC is a framework library that implements and MVC design pattern.
As for Razor, it's merely a templating library. That is, it allows you to define a page layout as text, and insert values at specific places (place-holders). It also allows code to be executed during the process of rendering a template, although this is discouraged in MVC except for very simple cases.
Razor is also used in ASP.NET WebPages technology, in those cases it tends to be more like PHP or classic asp in that all code exists in code blocks within the template itself. Both ASP.NET and WebPages use the Razor templating engine (also called a View Engine) but they use them in different ways.

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.

What is ASP.NET MVC not good for?

I'm a big fan of what ASP.NET MVC is doing, on many levels.
I'm about to take part in re-build of a very highly trafficked website, and I'm not which framework would be best (if any).
The site will need the following:
To support Javascript-heavy, highly interactive pages
But at the same time, provide underlying semantic HTML for search engines
Support multiple languages
Be skinnable
Expose a RESTful web-service API for partners
As far as I can tell, there's no reason not to use ASP.NET MVC for this.
I can present semantic HTML and layer Javascript on top using jQuery.
Multiple languages can be catered for using Resource files (same as at present).
Skinning can be done with CSS (it won't involve changes to the markup).
I can centralize business logic so that the Controllers and the WCF web-service use the same code.
But are there potential drawbacks to using MVC that I haven't considered?
I don't want to be the guy who picks a technology because it's cool but finds later down the track that it isn't very suitable for the job.
ASP.NET MVC is not good when all your doing is making a website that needs server-side code (but that's also true about ASP.NET also).
In your case I think MVC would be a great way to go. MVC has proven itself on high traffic websites (e.g. this one). However you must remember that MVC is new and changing. A library may not exists to do a specific task which means you'll have to write that code yourself.
Good luck on your rebuild!
You're good to go with MVC given what you've said about your project.
As far as I'm concerned, ASP.NET MVC is really only NOT good for situations where you have a large codebase in WebForms (meaning you have a lot of ASP.NET user controls, custom controls, etc). It's also not good if you are going to have people working on it who don't know what it's all about. Other than that, it's a pretty nice technology.
My two cents:
ASP.NET MVC is a great option but there is a little learning curve involved, so make sure your project plan/timeline has this handled. There might be developers on your team who might not be comfortable working with ASP.NET MVC, and this can cause possible delays (a lot of developers are still working in ASP.NET 1.1!).
#Alex: Lack of controls. Some features (like TreeView or Menu) are already implemented as Controls and it would be waste of time to reimplement them using mvc.
IMO the idea of using controls in ASP.NET MVC doesnt make much sense. You can create a treeview control using jQuery easily. Classic ASP.NET server controls carried a lot of baggage (viewstate etc) and hence ASP.NET MVC did not use any of those controls (though you can use helpers).
Finally, ASP.NET MVC is an alternative, not a replacement to Web Forms. I would not use ASP.NET MVC as it is still evolving, and my team is not very comfortable with it, but I guess slowly more and more programmers would shift to this (better) option.
I do not like ASP.NET MVC because of following reasons:
1.
Ugly routing API, there http://ayende.com/Blog/archive/2008/11/05/a-case-study-of-bad-api-design-asp.net-mvc-routing.aspx
is description of what is wrong.
By the way, friendly urls can be easily implemented without mvc
http://demo.liveui.net/bugtracker/Tasks/7
2.
Poor object model. It is proved that good software should consist of reusable components. There is nothing that can be reused in ASP.NET MVC based web site. For example, if you implemented smart drop down list once it will be difficult to use it again (even on the same web site).
3.
Lack of controls. Some features (like TreeView or Menu) are already implemented as Controls and it would be waste of time to reimplement them using mvc.
If I were you I would try to find some CMS and customize it for WebSite needs.
To responses:
YES. I know about ASP.NET controls disadvantages, but the question is about ASP.NET MVC. One can write a book about what is good and what is bad in ASP.NET but I do not think it is appropriate to discuss it here.
There are better ways of implementing MVC without using asp.net MVC. I have done it in the past, even before asp.net MVC came live. MVC is a pattern, not a technology, I do not understand why some people call it a Technology. You can separate all concerns by removing the code-behind from webforms and create your own controllers and routers and you will still have the advantage of the webform controls, etc to which most asp.net developers are used to use. asp.net mvc is nice for people whom do not really have the time to properly create an MVC app in a webforms environment and also to those whom do not have the time to architect a better solution. in conlcusion, asp.net mvc is good but there is a much better way of doing it and finally, MVC is NOT a technology.

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.

Resources