Comparison between ASP. net mvc and RAILS3

Source: Internet
Author: User

After entering the Web Age, the MVC framework entered the era of rapid evolution. The old MVC frameworks, such as Struts, were gradually abandoned due to low development efficiency, while the new version of MVC held high the banner of agility, gradually occupied the market, represented by Rails (ruby ),. net mvc (. NET), Django (Python), Symfony (PHP), etc. The ideas of these frameworks are similar. Here we list Rails3 and. net mvc to facilitate Web developers to migrate from Rails. net mvc, or vice versa, from. net mvc migration to Rails.

Generate a project 
Both Rails and. net mvc can generate the basic skeleton of the project, but the generation method is slightly different. Rails uses the command line method:

Java code
  1. Rails tapir


Microsoft provides a Project Wizard based on its powerful IDE.

The final directory structure is slightly different only in the test and configuration items.

Rails ASP. NET MVC
/App/models /Models
/App/controllers /Controllers
/App/views /Views
/Public/javascript /Scripts
/Public /Content
/Db /App_Data
/Test Independent VS Project
/Config /Global. asax,/Properties, Web. config



It is worth mentioning that one of the highlights of rails is that rails can be pre-configured with three different environments: development, testing, and final products. You can use the environment variable RAILS_ENV to perform simple switching ,. net mvc does not provide such a configuration environment. You can configure it manually.

Model 
Rails uses ActiveRecord as the model by default. Of course, switching to other frameworks is also very simple. The options include Neo4J, MongoDB, and DataMapper. In Rails, you still use command lines to create models. Rails generates some skeleton code, including models, migration tasks, and tests. You can use-o to select other models and-t to select other test frameworks:

Java code
  1. $ Rails g model customer name: string email: string
  2. Invoke active_record
  3. Create db/migrate/20100419094010_create_customers.rb
  4. Create app/models/customer. rb
  5. Invoke test_unit
  6. Create test/unit/customer_test.rb
  7. Create test/fixtures/customers. yml



Rails uses Sqlite3 as the background database by default, and Rails will generate a copy of the database for the development, testing, and production environments.

In Rails, all database operations are completed through scripts and migration. Migration in Rails should be the most valuable thing. When different developers modify a database at the same time, or when you upgrade the database in the existing production environment, the migration shows its powerful power:

Java code
  1. Class CreateCustomers <ActiveRecord: Migration
  2. # Called when migrating up to this version
  3. Def self. up
  4. Create_table: customers do | t |
  5. T. string: name
  6. T. string: email
  7. T. timestamps
  8. End
  9. End
  10. # Called when migrating down from this version
  11. Def self. down
  12. Drop_table: MERs
  13. End
  14. End



We can use the rake db: migrate command to migrate data to different database versions.

Unlike Rails ,. net mvc and bind a model Framework. You need to select a suitable Framework from the existing one. In this list, you can use nhib.pdf, Linq to SQL, Entity Framework, castle ActiveRecord or Ruby ActiveRecord, however. net mvc does not have the concept of migration, which is a bit regrettable.

In most cases, Linq To SQL is very suitable for project development.

Query Language 
Rails3 uses AREL (Active Record Relations) and LINQ-to-SQL uses LINQ. Both are pretty elegant languages

Java code
  1. # A simple query with AREL
  2. User. where (users [: name]. eq ('anders'). order ('users. id DESC '). limit (20)



Java code
  1. // The same with C #
  2. // Lambda Syntax
  3. Db. Users. where (u => u. Name = "Anders"). orderBy (u => u. Id). Take (20)
  4. // LINQ Syntax
  5. (From u in db. Users
  6. Where u. Name = "Anders"
  7. Orderby u. Id descending
  8. Select u). Take (20 );



In addition. NET uses Ruby ActiveRecord (with ironruby). Currently, no other frameworks provide functions similar to Ruby's findbyXXX, however, the method_missing of C #4.0 makes such a framework appear soon (such as nhib1_3.0)

Controller 
In. net mvc, if you add a Controller in the Controller directory, you will be guided by a friendly Wizard to add a Controller to the project, and you can even add basic CRUD functions.

Java code
  1. Public class CustomersController: Controller {
  2. // GET:/Customers/
  3. Public ActionResult Index (){
  4. Return View ();
  5. }
  6. // GET:/Customers/Details/5
  7. Public ActionResult Details (int id ){
  8. Return View ();
  9. }
  10. // GET:/Customers/Create
  11. Public ActionResult Create (){
  12. Return View ();
  13. }
  14. // POST:/Customers/Create
  15. [HttpPost]
  16. Public ActionResult Create (FormCollection collection ){
  17. Try {
  18. // TODO: Add insert logic here
  19. Return RedirectToAction ("Index ");
  20. } Catch {
  21. Return View ();
  22. }
  23. }
  24. }



Like the scaffolding code of Rails, 99% of the most basic code will be discarded, but it provides the foundation to let the program run and look at it.

Rails adds a controller to the project through the command line. You can also define the actions generated for the Controller in the command line.

Filter 
Rails can easily add a filter for an Action.

Java code
  1. Class ItemsController <ApplicationController
  2. Before_filter: require_user_admin,: only => [: destroy,: update]
  3. Before_filter: require_user,: only => [: new,: create]
  4. End


. NET is also unambiguous. You only need to overload OnActionExecuting to implement the same function:

Java code
  1. Override void OnActionExecuting (ActionExecutingContext filterContext)
  2. {
  3. Var action = filterContext. ActionDescriptor. ActionName;
  4. If (new List <string> {"Delete", "Edit"}. Contains (action )){
  5. RequireUserAdmin ();
  6. }
  7. If ("Create". Equals (action )){
  8. RequireUserAdmin ();
  9. }
  10. }


Or you can use the. NET attribute to make it more beautiful.

Java code
  1. [RequireUserAdmin ("Delete", "Edit")]
  2. [RequireUser ("Create")]
  3. Public class CustomersController: Controller



Routing 
In Rails, you can modify routes. rb to modify the route. The default Rails route is configured as RESTful:

Java code
  1. Tapir: Application. routes. draw do | map |
  2. Resources: animals
  3. Get "customer/index"
  4. Get "customer/create"
  5. Match "/: year (/: month (/: day)" => "info # about ",
  6. : Constraints >{: year =>/ \ d {4 }/,
  7. : Month =>/\ d {2 }/,
  8. : Day =>/\ d {2 }/}
  9. Match "/secret" => "info # about ",
  10. : Constraints =>{: user_agent =>/ Firefox /}
  11. End


With rake routes, you can quickly view the route results.

The routing of ASP. net mvc is a little complicated, but it is also powerful:

Java code
  1. // Global. asax. cs
  2. Public class MvcApplication: System. Web. HttpApplication {
  3. Public static void RegisterRoutes (RouteCollection routes ){
  4. Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
  5. // Constrained route
  6. Routes. MapRoute ("Product", "Product/{productId }",
  7. New {controller = "Product", action = "Details "},
  8. New {productId = @ "\ d +"}); // Constraint
  9. // Route with custom constraint, defined below
  10. Routes. MapRoute ("Admin", "Admin/{action }",
  11. New {controller = "Admin "},
  12. New {isLocal = new LocalhostConstraint ()});
  13. }
  14. ...
  15. }
  16. Public class LocalhostConstraint: IRouteConstraint {
  17. Public bool Match (HttpContextBase httpContext, Route route,
  18. String parameterName, RouteValueDictionary values,
  19. RouteDirection routeDirection)
  20. {
  21. Return httpContext. Request. IsLocal;
  22. }
  23. }



View 
The two views are very similar. When a controller is added, the corresponding View is automatically created. The rule is similar: the folder where the View is located is named by the Controller name, the View File Name Is the action Command of the controller, both of which provide the ability to create a scaffold view from a model.

Partials 
Rails and Asp. net mvc both provide the ability to include part of HTML files in files. ASP. net mvc files use ASP, while Rails uses ERB or HAML by default.

Java code
  1. <! -- Rails -->
  2. <% = Render 'form' %>



Java code
  1. <! -- ASP. net mvc -->
  2. <% Html. RenderPartial ("Form", Model); %>



. Net mvc 2 has made some improvements and advocates using two alternative methods to generate code:

Java code
  1. <% = DisplayFor ("Address", m => m. Address) %>
  2. <% = EditorFor ("Address", m => m. Address) %>




Conclusion 
This article provides a quick view of Rails and. net mvc to allow programmers with corresponding programming experience to quickly understand another framework. Both Rails and. net mvc are just a tool. A good programmer should be able to play with his tools without being manipulated by tools.


Refer:
Http://blog.jayway.com/2010/04/23/asp-net-mvc-vs-rails3/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.