I like Mvc for these reasons.

Source: Internet
Author: User

I like Mvc for these reasons.

Recently, I liked mvc, and I had some insights on mvc. I admire the technologies that Microsoft has brought to. net, mvc and ef.

1. Create a project with built-in boot13c

Boot13c is a responsive UI library that can quickly build a responsive interface. If there is no artist and there is no high requirement on the interface, it can be used directly and very convenient.

Recommendation websites for boot13c

Http://getbootstrap.com/

Http://www.bootcss.com/

2. Flexible url routing control and seo-friendly
  1. Public class RouteConfig
  2. {
  3. Public static void RegisterRoutes (RouteCollection routes)
  4. {
  5. Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
  6. Routes. MapRoute (
  7. Name: "Default ",
  8. Url: "{controller}/{action}/{id }",
  9. Defaults: new {controller = "Home", action = "Index", id = UrlParameter. Optional}
  10. );
  11. }
  12. }

 

This is the default route registered by RouteConfig. The static method of this class, RegisterRoutes, is called when the website is started.

Unlike webform, a dynamic url address corresponds to a local aspx file, while MVC corresponds to an Action (public method) in a Controller ). Mvc corresponds to "/Home/About", which corresponds to the Action named About of HomeController. You can set the correspondence between the URL address and the action of controllercompletely according to your requirements, so as to be configured as pseudo static at the end of .html.

In my previous article, you can refer to "Custom route routing mechanism".

3. flexible view Engine

By default, the mvc View File. cshtml will automatically put the views of the actions of the same Controller in a folder.

Corresponding View File structure

The built-in view of the mvc view is the razor engine, which can be strongly bound to the view, ensuring security and performance.

It is very easy to specify the model type for the view.

Use return View (xx) in Contoller)

Xx is a corresponding model object.

View usage:

@ Model xxx. Models. xx

In this way, the view can be bound with the @ Model. Field.

A view can be like defining a shared part of Layout (just like the master page of The Webform master). The shared html such as the header, footer, and menu navigation can be placed in Layout, for html with the same local location, you can use @ Html. action ("actionName", "controllerName") method to bind a local view (like a Webform user control)

 

 

The local view corresponding to the Action can also define that the output cache OutputCache unit is minute, so that the next request is directly retrieved from the cache, improving the program efficiency. I usually add cache to actions that do not change frequently. [ChildActionOnly] indicates that views can only be referenced and cannot be accessed directly in a browser.

3.1. Custom view Engine

 

In this way, the mvc view topic can be implemented. A website can create topics of different styles. You can bind a view to each topic.

To make the custom view engine take effect, add the following code to Global. asax to disable the default view engine.

  1. ViewEngines. Engines. Clear ();
  2. ViewEngines. Engines. Add (new CustomRazorViewEngine ());
4. Model binding

Action parameters can be independent parameters or a model object. mvc can obtain parameters from the request and bind corresponding fields to the model. In this way, the automatic assembly function is implemented when the Form is submitted, without the need to assign a value to the model as follows: Request. Form ["xx.

By default, parameters of mvc are bound in the following order.

Request. Form =, RouteData. Values =, Request. QueryString =, Request. Files

Assume that the parameter id of an Action will get the id value in order below, and it will not be searched for below once it is found.

1. Request. Form ["id"]

2. RouteData. Values ["id"]

3. Request. QueryString ["id"]

4. Request. Files ["id"]

Add a feature during development, bind a model object, and view code:

@model MvcModels.Models.Person@{ViewBag.Title = "CreatePerson";}

 

 

Background code

[HttpPost] public ActionResult CreatePerson (Person model) {return View ("Index", model);} in this way, the foreground form value will correspond to the corresponding fields of the model. Of course, you can also specify the fields to Bind to public ActionResult AddSummary ([Bind (Include = "HomeAddress", Exclude = "Country")] AddressSummary summary) {// do somethingreturn View (summary );}

 

MVC validation is very good. It comes with a non-null check, type check, and complex regular expressions.
[Requred]
Public string Name {get; set ;}
The Name field is required.

4.1 Binder binding

Use the IModelBinder interface to customize the Binder class of a shopping cart

 

Public class CartModelBinder: IModelBinder {private const string sessionKey = "Cart"; public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {// read Cart cart Cart = (Cart) from Session) controllerContext. httpContext. session [sessionKey]; if (cart = null) {cart = new Cart (); controllerContext. httpContext. session [sessionKey] = cart;} return cart ;}}

 

 

Add the code for the Application_Start method in Global. asax to the Model binding set and add the preceding custom CartModelBinder class.

ModelBinders. Binders. Add (typeof (Cart), new CartModelBinder ());

In this way, the Cart object of subsequent actions is as follows:

 

  1. Public ViewResult Summary (Cart cart)
  2. {
  3. Return View (cart );
  4. }

 

It is automatically bound, that is, the object whose key is Cart from the Session.

 

5. Flexible Controller

The Controller expansion of mvc is also flexible.

The above is the execution process of the MVC Framework Program. The ControllerFactory, Controller, and Action Invoker in the figure above can be fully customized and extended.

The Controller we created inherits System. Web. Mvc. Controller by default. This is an abstract class. In fact, it provides us with many basic implementations.

Many of its methods are defined as virtual methods, so if we want to implement our own personalized things, we can also rewrite the methods in it.

5.1 customize a ControllerFactory
using System;using System.Web.Mvc;using System.Web.Routing;using System.Web.SessionState;using ControllerExtensibility.Controllers;namespace ControllerExtensibility.Infrastructure {public class CustomControllerFactory: IControllerFactory {public IController CreateController(RequestContext requestContext,string controllerName) {Type targetType = null;switch (controllerName) {case "Product":targetType = typeof(ProductController);break;case "Customer":targetType = typeof(CustomerController);break;default:requestContext.RouteData.Values["controller"] = "Product";targetType = typeof(ProductController);break;}return targetType == null ? null :(IController)DependencyResolver.Current.GetService(targetType);}public SessionStateBehavior GetControllerSessionBehavior(RequestContextrequestContext, string controllerName) {return SessionStateBehavior.Default;}public void ReleaseController(IController controller) {IDisposable disposable = controller as IDisposable;if (disposable != null) {disposable.Dispose();}}}}

 

 

CustomControllerFactory is responsible for creating the Controller object based on the obtained route information.

To make the custom mmcontrollerfactory take effect, add the registration code in the Application_Start () method.

 

  1. ControllerBuilder. Current. SetControllerFactory (new CustomControllerFactory ());

 

6. AOP Aspect-Oriented Programming

Java's Spring framework has powerful AOP (Aspect-Oriented Programming), which greatly reduces the coupling of software modules and improves code reuse and maintainability.

ASP. net mvc has various Filter filters, which are equivalent to the AOP technology. It can be applied to identity authentication, logging, and Exception Handling. In this way, the core business only cares about its own logic code, and the final code will not contain Business Code authentication and log-related code.

I have previously written an article about mvc's aop practice-using MVC5 Filter to determine the logon status.

 

7. IOC control Inversion

The. Net IOC framework is also popular among many, such as Autofac, Castle Windsor, Unity, Spring. NET, StructureMap, and Ninject. MVC uses these frameworks for good integration. Some do not need to write their own IOC framework and MVC integration code. Like Autofac, MVC5, MVC2, 3, and 4 all have existing integrated code, such.

You can directly install it in your own MVC project. If the IOC framework you use does not find the MVC integration package in nuget, you can easily write it yourself.

For details, refer to my previous article IOC practices -- using Autofac to implement the IOC control reversal method of MVC5.0

8. Easy Unit Testing

You can use the moq framework to easily simulate real Web requests without testing the Action and Controller through IIS on the Web server.

The Controller and Action methods of mvc can easily perform unit tests.

If you want to test the return value of an Action method, you do not need to parse any HTML. You only need to monitor the ActionResult type objects returned by the Action.

You do not need to simulate user requests. The model of the MVC Framework binds objects as parameters of the Action method, and then returns the corresponding results. The simplest test is to pass in specific parameters to directly call

Action method. For example, to test an Action, a specified View is returned.

 

  1. Public ViewResult Index (){
  2. Return View ("Homepage ");
  3. }

 

Test code:

 

Using System; using Microsoft. visual Studio. testTools. unitTesting; using ControllersAndActions. controllers; using System. web. mvc; namespace ControllersAndActions. tests {[TestClass] public class ActionTests {[TestMethod] public void ViewSelectionTest () {// create the ControllerExampleController target = new ExampleController (); // call ActionViewResult result = target. index (); // judge the test result Assert. areEqual ("Homepage", result. viewName );}}}

 

 

9. Open Source

MVC is an open-source framework, while NuGet is a very useful package management tool for VS. There are many useful class libraries on it. Search for mvc and the following results are displayed.

You can see many useful class libraries, PagedList. Mvc and Grid. Mvc.

9. Perfect Combination of entityframework

To add a Controller to the MVC5 project, you can select "MVC5 Controller containing view (using Entity Framework)", such a Model's add, delete, modify, and query related views and actions are automatically generated for you. You only need to modify the settings as needed. This greatly improves the development speed, which is very useful for the development management backend.

10. Summary

Summary: I have always thought that. net is relatively easy to get started, because Microsoft has encapsulated many things for you and it is difficult to become a master. Unlike many open-source frameworks in java, you can learn a lot about software architecture and design patterns, such as interface-oriented programming, AOP, and IOC. However. net, such as MVC, EF, and even now. NET Framework is also open-source, and more research is being conducted. net now, I can see that every part of MVC is flexible and can be rewritten and customized according to your own needs. It is recommended that you want to become a master or architect. It is necessary to carefully study the source code of MVC and the original code, because you can learn a lot of skills related to design patterns, software architecture, and software design, it is helpful for improving our technical capabilities.

Related Article

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.