These reasons make me like MVC

Source: Internet
Author: User
Tags button type httpcontext

The recent period has made me like MVC, an insight into MVC, and the technology that Microsoft brings to. NET, Mvc,ef

1, create the project built-in Bootsrap

Bootsrap is a responsive UI library, can quickly build a responsive interface, if there is no art, the interface requirements are not very high, it can directly function, very convenient.

Recommended Sites for Bootsrap

http://getbootstrap.com/

http://www.bootcss.com/

2, URL routing control flexible, 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 routeconfig to register the default route. The static method of this class registerroutes is called when the Web site is started.

MVC is not like WebForm, where a dynamic URL address corresponds to a local aspx file, and MVC is an action (public method) that corresponds to a controller. MVC is the corresponding "/home/about" corresponding to the HomeController's name is about action. The corresponding relationship between this URL and the controller's action can be set according to your requirements and can even be configured as a. Pseudo-static at the end of HTML

An article I wrote earlier can look at "Custom route routing mechanism"

3, the flexibility of the view engine

The MVC view file is created by default. Cshtml will automatically place the view of the same controller's action in a folder.

Corresponding view file structure

The view that comes with the MVC view is the Razor engine, which can be strongly typed to bind views, secure, and performance guaranteed.

It is simple to specify the model type of the view

Use return View (XX) in Contoller

XX is a corresponding model object.

Views using:

@model xxx. models.xx

This allows the view to be bound with the @model field.

Views can be like defining a common part of layout (like WebForm's Master master page), headers, footers, menu navigation, and other common HTML can be placed in layout, for local multiple places the same HTML, you can use @html.action ( "ActionName", "Controllername") method to bind a partial view (just like the WebForm user control)

The local view of the action can also define the output cache outputcache units are minutes so that the next request is taken directly from the cache, improving the efficiency of the program. I always add the cache to actions that don't change frequently. Plus [childactiononly] means it can only be referenced through a view and cannot be accessed directly from the browser.

3.1. Custom View engine

This allows you to implement the MVC view theme, which allows you to create themes of different styles, each bound to a view.

For the custom view engine to take effect it is also necessary to add the following code in Global.asax to disable the default view engine.

    1. Viewengines. Engines. Clear();
    2. Viewengines. Engines. Add(new customrazorviewengine());
4. Model Binding

An action parameter can be a single parameter or a model object, and MVC can get the corresponding field from the request to the parameter binding to the model. This enables the automatic assembly of the form when it is submitted, without the need for something like this: request.form["xx"] to get the value assigned to the model.

The default parameter bindings for MVC are in the following order.

Request.form= "routedata.values=" request.querystring= "request.files

Suppose a parameter ID for an action, the value of the ID is given sequentially from the following, and once found it will not be looked down.

1. request.form["id"]

2. routedata.values["id"]

3. request.querystring["id"]

4. request.files["id"]

An add function in the practice development process, binding a model object, the View code:

" Createperson " ;} @using (Html.BeginForm ()) {<div> @Html. labelfor (M = m.personid) @Html. Editorfor (M=>m.personid) </div><div> @Html. labelfor (M = m.firstname) @Html. Editorfor (m= >m.firstname) </div><div> @Html. labelfor (M = m.lastname) @Html. Editorfor (m=>m.lastname) </ Div><div> @Html. labelfor (M = m.role) @Html. Editorfor (m=>m.role) </div><button type="  Submit">Submit</button>}

Background code

[HttpPost] PublicActionResult Createperson (person model) {returnView ("Index", model);} The value of the foreground form will correspond to the corresponding field in the model. Of course, you can also specify which fields to bind Publicactionresult addsummary ([Bind (Include="homeaddress", Exclude ="Country")]addresssummary summary) {//Do somethingreturnView (summary);}

MVC's checksum is very good, with a non-empty test, type checking, and can also write complex regular expressions.
[Requred]
public string Name{get;set;}
The above indicates that the name field is required.

4.1 Customizing binder Bindings

Customizing the Binder class for a shopping cart using the Imodelbinder interface

 Public classcartmodelbinder:imodelbinder{Private Const stringSessionKey ="Cart"; Public ObjectBindmodel (controllercontext controllercontext,modelbindingcontext bindingcontext) {//Read Shopping Cart object from sessionCart cart =(Cart) Controllercontext.httpcontext.session[sessionkey];if(Cart = =NULL) {cart=NewCart (); Controllercontext.httpcontext.session[sessionkey]=cart;}returncart;}}

The Application_Start method in Global.asax adds code for the model binding collection to the above custom Cartmodelbinder class.

ModelBinders.Binders.Add (typeof (Cart), New Cartmodelbinder ());

The Cart object for the subsequent action is as follows:

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

will automatically bind, that is, from the session to take the key to the Cart object.

5. Flexible controller

MVC's controller expansion is also flexible

The above is the implementation process of the MVC Framework Program, the above diagram of the controllerfactory,controller,action invoker can fully customize the extension.

The controller we created is actually the default inherited System.Web.Mvc.Controller, which is an abstract class, in fact it provides us with a lot of basic implementation

Many of its methods are defined as virtual methods, so if we want to implement our own personalization, we can rewrite the method.

5.1. Customizing a Controllerfactory
usingSystem;usingSYSTEM.WEB.MVC;usingSystem.Web.Routing;usingSystem.Web.SessionState;usingcontrollerextensibility.controllers;namespaceControllerextensibility.infrastructure { Public classCustomcontrollerfactory:icontrollerfactory { PublicIController Createcontroller (RequestContext requestcontext,stringcontrollername) {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;}returnTargetType = =NULL?NULL:(IController) DependencyResolver.Current.GetService (TargetType);} PublicSessionstatebehavior Getcontrollersessionbehavior (Requestcontextrequestcontext,stringcontrollername) {returnSessionstatebehavior.default;} Public voidReleasecontroller (IController Controller) {IDisposable disposable= Controller asIDisposable;if(Disposable! =NULL) {disposable. Dispose (); }}}}

The customcontrollerfactory responsibility is to create the appropriate controller object based on the fetch to routing information on request

You need to include the registration code in the Application_Start () method for the custom customcontrollerfactory to take effect

    1. Controllerbuilder. Current. Setcontrollerfactory(new customcontrollerfactory());

6. AOP Aspect-oriented programming

Java's Spring Framework AOP (aspect-oriented programming) is very powerful, the advantage of AOP is greatly reduced the coupling of software modules, improve the reuse and maintenance of code.

ASP. NET MVC has a variety of filter filters, which are equivalent to AOP techniques. Can apply to authentication, logging, exception handling, so that the core business only care about their own logic code is, the final code will not be mixed with business code authentication, log-related code.

I wrote an AOP article about MVC before, AOP practice--using MVC5 filter to make login state judgments

7. IOC control reversal

. NET aspect of the IOC framework is also a lot of mainstream has AUTOFAC, Castle Windsor, Unity, Spring.net, StructureMap, Ninject and so on. MVC also integrates well with these frameworks. Some do not have to write their own IOC framework and MVC integration code. Like Autofac have MVC5 and MVC2, 3, 4 have existing integration code, such as.

Direct installation can be used in your own MVC project, and it's easy to write your own if you use an IOC framework that doesn't find the MVC integration pack in NuGet.

Please look at my previous article. IOC Practice--implementation of MVC5.0 's IOC control inversion method with AUTOFAC

8, Unit Testing Easy

You can use the MOQ framework to simulate a real Web request without testing the action and controller through Web server IIS and so on.

Both the Controller and action methods of MVC can be easily used for unit testing.

If you want to test the return value of an action method, you do not have to parse any HTML. You only need to monitor the action's return value ActionResult type of object.

Instead of impersonating a user request, the model binding object of the MVC framework, as an argument to the action method, then returns the corresponding result. The simplest test is that you pass in a specific parameter directly

Action method, you can. For example, to test if an action is really going to return a specified view

    1. Public ViewResult Index() {
    2. return View("homepage");
    3. }

Test code:

usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingcontrollersandactions.controllers;usingSYSTEM.WEB.MVC;namespacecontrollersandactions.tests {[TestClass] Public classactiontests {[TestMethod] Public voidviewselectiontest () {//Create a Controller to testExamplecontroller target =NewExamplecontroller ();//Invoke ActionViewResult result =Target. Index ();//Judging test ResultsAssert.AreEqual ("Homepage", result. ViewName); }}}

9. Open Source

MVC is an open source framework, and NuGet is a very useful package management tool with a lot of useful class libraries, and the following results are found in MVC.

You can see a lot of useful class libraries, pagination (PAGEDLIST.MVC), Grid.mvc.

9, EntityFramework Perfect cooperation

MVC5 Project Add controller You can select the "MVC5 Controllers with views (using the entity Framework)" so that the associated view and action of a model are automatically generated for you, You just need to change it according to your needs and basically you can use it. This greatly improve the development speed, for the development of management background this is too easy to use.

10. Summary

Summary: I have always felt that. NET is easy to get started, because a lot of things Microsoft has been packaged for you, to become a master more difficult, unlike Java a lot of open-source framework, from which you can learn a lot of software architecture and design patterns such things, for example, interface-oriented programming, AOP,IOC this kind of. But along with. NET-related things like MVC, EF, and even now the. NET Framework also open source, research more and more, these. NET now also can, I write above can see each part of MVC is very flexible, can completely according to own need rewrite, custom-made. Recommended to be a master or architect, it is necessary to carefully study the source of MVC and the original, because from the inside can learn a lot of design patterns, software architecture, software design-related skills, to enhance our technical ability is very helpful.

These reasons make me like MVC

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.