The basic article of ASP.net MVC Summary (ii.) Practical skills

Source: Internet
Author: User

In addition to this note, sharing all of a sudden, the basic MVC everything is introduced, but are very basic things. Originally intended to publish a finished, but found something a little more, so divided into two articles, this is the last one!

1.asp.net MVC Request Process

1

2.Controller

(1) The controller plays the role of processing client requests in ASP.net MVC

1 must implement System.Web.Mvc.IController interface

-> usually directly inherits the System.Web.MVC.Controller class

2 must end with controller

3 to handle specific client requests through different action

3.Action

(1) refers to a type that inherits the return value defined in the System.Web.Mvc.Controller class that is compatible

(2) ActionResult method

Copy Code code as follows:

Namespace Mvcapplication.controllers
{
public class Homecontroller:controller
{
Public ActionResult Index ()
{
Viewbag.message= "Han Guanlong";
return View ();
}
}
}

(3) The ActionResult of ASP.net MVC3

    

(4) Matters needing attention

1 The action that can be accessed through the URL must be publicly available (public) method

2 if the [Nonaction] property is marked, this action cannot be accessed through the URL

3) By default, the action method name is the action name (the name accessed by the URL), and a specific action name can be marked by [ActionName ("Otheractionname")] if there is a special need.

4 we can use [httppost][httpget] to differentiate the action of the same name to handle different request actions

4.asp.net Routing Routing, filter

(1) The responsibility of the ASP.net routing module (module) is to map incoming client (browser) requests to specific MVC Controller Actions

(2) Routing mechanism

1 routing Engine-map URLs to Controlller

Copy Code code as follows:

public static void RegisterRoutes (RouteCollection routes)
{
Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
Routes. Maproute (
' Default ',//Routing name
' {controller}/{action}/{id} ',//URL with parameter
New {controller = "Home", action = "Index", id = urlparameter.optional}//Parameter defaults
);
}
protected void Application_Start ()
{
RegisterRoutes (routetable.routes);
}

2)/PRODUCTS/DETAIL/8

Copy Code code as follows:

Routes. Maproute (
' Default ',//Routing name
' {controller}/{action}/{id} ',//URL with parameter
);
public class Productscontroller:controller
{
Public ActionResult Details (int id)
{
return View ();
}
Public ActionResult Edit (int id)
{
return View ();
}
}

5. Routing Changes in MVC3

(1) from the system.web.routing3.5 assembly to the System.Web 4 assembly, became a part of the basic services.

(2) The module routing in asp.net 4 is registered in the root Web.config and does not require you to register separately in the web.config of your application

(3) UrlRoutingModule handled an event that reduced one, dealing only with Postresolverequestcache events

(4) HttpRequest adds a new RequestContext attribute

(5) Added Pageroutehandler, support WebForm routing function

(6) 4 Mappageroute Overloaded methods are added to the routecollection, adding routing rules is more convenient

6. Routing Benefits

(1) Easy to implement rest services

(2) URL-friendly, conducive to SEO and enhance the user experience

(3) Controller and action invocation rules can be customized to reduce coupling and improve flexibility

7. Filter

(1) filter is an AOP mode, can be a series of operations crosscutting interference means, it is very much decoupled dependencies, so that our code more concise, more functional

(2) 4 class filter interfaces are available in asp.net mvc

1) Iactionfilter

2) Iauthorizationfilter

3) Iexceptionfilter

4) Iresultfilter

(3) asp.net MVC provides common filter implementations such as Outputcacheattribute,handlerrorattribute,authorizeattribute

(4) The insertion process of filter

1) Taking Actionfilter as an example

      

8. Filter in the Sp.net MVC3

(1) provides the Global register filter function

(2) Provide outputcache support to Childaction

1) use with [childactiononly]

9. Model

(1) MVC model is mainly responsible for maintaining the data state, the data from the data storage to retrieve and pass to the controller, the client transmitted data processed and then transmitted back to the data storage system, is a heavy layer of MVC

(2) The ASP.net MVC framework itself does not care about data storage systems, and simplifies the use of the model with some additional help classes and model binding mechanisms

1 Self-binding mechanism

2 self-verification mechanism

(3) Improvement of asp.net MVC3 model

1) asp.net MVC3 model mainly improves the verification mechanism

-> Data Validation (annotations)

-> Client Validation

-> Remote Authentication (Validation)

-> self-validation (self Validation)

(4) Data validation

1) validated by System.ComponentModel.DataAnnotations collection of methods, and has some facilitation effects on client verification

2 The attribute of custom validation can be implemented by inheriting Validationattribute

(5) Client Authentication

1 Validation plug-ins using jquery

2) Jquery.validate.unobtrusive.mis.js Implement client Authentication

-> enable client-side authentication

<appSettings>

<add key= "clientvalidationenabled" value= "true"/>

<add key= "unobtrusivejavascriptenabled" value= "true"/>

</appSettings>

-> reference jquery

<script src= "Http://www.cnblogs.com/Scripts/jquery.validate.min.js" type= "Text/javascript" ></script>

<script src= "Http://www.cnblogs.com/Scripts/jquery.validate.unobtrusive.min.js" type= "Text/javascript" > </script>

Special verification of->

@{

Html.enableclientvalidation ();

}

(6) Remote Authentication

1 in the model of the use of similar to RequiredAttribute

1 [Remote ("Verified action name", "Controller name", errormessage= "remotely authenticated as failed error message")]

2) Note

1 The action for Remote authentication must be httpget and the post submission is invalid

2 The result returned by the action is Jsonresult, not directly returning a Boolean value

(7) Self-verification

1 in model with Validationcontext and Validationresult to provide validation

Copy Code code as follows:

Public ienumerable<validationresult> Validate (Validationcontext validationresult)
{
if (enddate<=startdate)
{
Yield return new Validationresult ("End time must be greater than start time");
}
}

10. Best Practices

(1) Layered design

1) Multiple projects

2) Separation of attention points

3) Replaceable data access layer

(2) Repository mode (business layer)

1 The data additions and deletions to the check (CRUD) operation package into the repository

2 business logic/data validation package to service

3) Controller calls Respository and service

(3) PRG Mode (method)

1) POST

2) Redirect

3) Get

4 PRG mode is used to ensure that the modified data occurs only once

(4) Keep the amount of code in the view minimized

1 The view does not contain the logical code of data processing

2 to avoid large blocks of code in the view

3) Building multiple attempts/partial views

4 use appropriate @helper and @function syntax

(5) say "Goodbye" to the magic string.

1) ASPX mode

@ViewData ["Message"]

@ViewData ["TotalCount"]

2) Razor Mode

@Model. Message

@Model. TotalCount

3 Try to use the specific model, and avoid using viewdata/viewbag

(6) Domainmodel (domain model)! =viewmodel (view model)

1) Meet the requirements of the minimum ViewModel

1) Effective verification

2) High Security

3) High Performance

2 use some mapping tools to do bidirectional mapping fill

1) Automapper,emitmapper,valueinjecter

2) Custom Orm-generpoint.orm

3 The use of dedicated ViewModel fill logic, easy to resolve internationalization/localization

(7) using the new Ajax Helper

1 Web.config Sino-German appsettings

<add key= "unobtrusivejavascriptenabled" value= "true" >

2) Reference Jquery.unobtrusive-ajax.js in the view

3 Call Ajax Helpers in view

1 @Ajax. ActionLink ("Home", "Index", New ajaxoptions{updatetargetid= "main"})

2) <a data-ajax= "true" data-ajax-mode= "Replace" data-ajax-update= "#content" href= "/" >Home</a>

(8) Write HTML code as much as possible in the view

1 Write pure HTML code whenever possible

2 Do not intentionally customize the helper of Html.submit and so on in order to hide HTML

3 Do not use the WebForm control as far as possible to do view code rendering

(9) IIS Express 7.5

1 with complete Web server functionality

1) SSL

2) URL Rewrite

3 The configuration of <System.webServer> can be tested locally

4) IIS7. x Other Template collections

2) Lightweight

1) <5m

2 No Administrator account required

3) High Performance

11. About performance optimization of soft power

(1) Understand the basic knowledge of Http,cache,ajax

(2) able to conduct analysis and architecture planning for the overall web execution environment

(3) able to design a proper caching strategy

(4) Be able to further target the performance of the website Data speech analysis

12. Hard for performance optimization

(1) familiar with. net/c#/asp.net MVC Framework and Core principles

(2) can further plan for the project, do a good job of separation of attention points design

(3) familiar with profiling technology, can analyze the performance bottleneck of a link

(4) able to optimize the code for various environments, improve the performance of the program

13. Determining the key elements of Web performance

(1) Fundamentals of Web performance optimization-http

1 HTTP is stateless

2 A Web page contains N-Times HTTP requests

(2) Analysis of HTTP status when Web page is open

1) Fiddler

2) IE10 Developer Tools

(3) Client optimization

1 The number of HTTP requests is reduced

2) The bandwidth used by the download

3 The length of time for DNS queries

4) The speed of the CSS display

5 The speed of JavaScript calls

(4) Service-side optimization

1) IIS

-> Control Client

HTTP Cache Control

-> Control Server Side

To count out the cache (Output Caching)

Increase database query speed

2) asp.net MVC

-> Call Performance Improvement

-> the appropriate caching policy

(5) [Seesionstate]

1) using the sessionstate property

How to control the Controller access phase State data (session)

2) Note: You cannot use TempData to pass information after closing session

(6) [OutputCache]

1) html.action and html.renderaction support output Caching

->@{html.renderaction ("ActionName")}

-> @Html. Action ("ActionName")

2) Childaction finally supports OutputCache properties

->[childactiononly]

-> only supports Duration,varybycustom and VaryByParam parameters

-> cannot use CacheProfile parameter

(7) Change the default setting of Viewengine

1 Remove the extra viewengine to increase the speed of the parse view

->viewengines.engines.clear ();

->viewengines.engines.add (New Razorviewengine ());

2 can also change the order in which the view is loaded in this way

-> default is Webformviewengine priority processing

->viewengines.engines.add (New Webformviewengine ());

(8) Avoid breaking into null to view

1) html.textboxfor (m=>m.name)

-> can cause exception when passed in null, but will be try/catch off

->public Actionresultinsert () {

Return View (new products ());

}

(9) Turn off the Web.config debug mode

1) <compilation debug= "False" targetframework= "4.0"/>

The basic article is here, the following article we have some in-depth knowledge, we look forward to the next bar

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.