Basic knowledge of MVC

Source: Internet
Author: User
Tags website performance

1.asp.net MVC Request Process

1

2.Controller

(1) Controller plays the role of processing client requests in ASP.

1) System.Web.Mvc.IController interface must be implemented

Usually directly inherits the System.Web.MVC.Controller class

2) must end with controller

3) Handle specific client requests with different actions

3.Action

(1) means the type of the return value defined in the inherited System.Web.Mvc.Controller class can be compatible

(2) ActionResult method

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

(3) ASP. MVC3 ActionResult

    

(4) Precautions

1) An action that can be accessed via a URL must be a public method

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

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

4) We can use [httppost][httpget] to differentiate between actions with the same name that handle different requests.

4.asp.net Routing Routing, filters

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

(2) Routing mechanism

1) Routing Engine-map URLs to Controlller

Copy CodeThe code is as follows:
public static void RegisterRoutes (RouteCollection routes)
{
Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
Routes. MapRoute (
"Default",//route name
' {controller}/{action}/{id} ',//URL with parameter
New {controller = "Home", action = "Index", id = urlparameter.optional}//parameter default value
);
}
protected void Application_Start ()
{
RegisterRoutes (routetable.routes);
}

2)/PRODUCTS/DETAIL/8

Copy CodeThe code is as follows:
Routes. MapRoute (
"Default",//route 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) Transferred from the system.web.routing3.5 assembly to the System.Web 4 assembly, as part of the basic service.

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

(3) UrlRoutingModule processed events reduced by one, handling only Postresolverequestcache events

(4) HttpRequest adds a new RequestContext attribute

(5) Added Pageroutehandler, support WebForm routing function

(6) The routecollection adds 4 Mappageroute overloaded methods, which makes it easier to add routing rules

6. Routing Benefits

(1) Easy to implement rest services

(2) URL-friendly for SEO and enhanced user experience

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

7. Filter

(1) filter is an AOP pattern, a means of crosscutting interference with a range of operations, which largely decouples dependencies, making our code more concise and more versatile

(2) 4 types of filter interfaces are available in ASP.

1) Iactionfilter

2) Iauthorizationfilter

3) Iexceptionfilter

4) Iresultfilter

(3) Common filter implementations such as Outputcacheattribute,handlerrorattribute,authorizeattribute are provided in ASP.

(4) The cut-in process of filter

1) Take Actionfilter as an example

      

8. Filter in Sp.net MVC3

(1) provides the global registration filter function

(2) Provide outputcache support for childaction

1) use with [childactiononly]

9. Model

(1) The model in MVC is mainly responsible for maintaining the data state, retrieving data from the data memory and passing it to the controller, and the data transmitted by the client is processed and then returned to the data storage system, which is the heavier layer of MVC.

(2) The ASP itself does not care about the data storage system, and simplifies the use of the model through some additional helper classes and model binding mechanisms.

1) Self-binding mechanism

2) Self-validating mechanism

(3) Improvements to the ASP. MVC3 model

1) the ASP. MVC3 model mainly improves the authentication mechanism

Data validation (Annotations)

Client-side validation (Validation)

Remote Authentication (remotely Validation)

-I self-Validation

(4) Data validation

1) validation through the System.ComponentModel.DataAnnotations method set, and has some convenience effect on client validation

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

(5) Client Authentication

1) Use jquery's validation plugin

2) Jquery.validate.unobtrusive.mis.js implement client-side validation

, enable client-side validation

<appSettings>

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

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

</appSettings>

--Quote 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 validation

@{

Html.enableclientvalidation ();

}

(6) Remote Authentication

1) similar to RequiredAttribute used in model

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

2) Note

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

2) The result of the action return is Jsonresult, not directly returning a Boolean value

(7) Self-verification

1) provide validation in model with Validationcontext and Validationresult

Copy CodeThe code is 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 concerns

3) Replaceable data access layer

(2) Repository mode (business layer)

1) package The data additions and deletions (CRUD) operations into the repository

2) business logic/data validation encapsulated into service

3) Controller calls Respository and service

(3) PRG Mode (method)

1) POST

2) Redirect

3) GET

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

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

1) do not include logical code for data processing in the view

2) to avoid containing large blocks of code in the view

3) Build multiple attempts/detail views

4) Use the 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 a specific model and avoid using viewdata/viewbag

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

1) Minimum ViewModel to meet the requirements

1) Effective validation

2) High safety

3) High Performance

2) Use some mapping tools to do two-way mapping padding

1) Automapper,emitmapper,valueinjecter

2) Custom Orm-generpoint.orm

3) easily resolve internationalization/localization with dedicated ViewModel fill logic

(7) using the new Ajax Helper

1) Web. config appsettings de

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

2) Reference jquery.unobtrusive-ajax.js in view

3) Call Ajax Helpers in the 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 the HTML code as much as possible in the view

1) write plain HTML code as much as possible

2) do not intentionally customize helper html.submit, in order to hide HTML

3) Render the view code without using the WebForm control as much as possible

(9) IIS Express 7.5

1) Full Web server functionality

1) SSL

2) URL Rewriting

3) can test the <System.webServer> configuration locally

4) IIS7. x Other Template collections

2) Lightweight

1) <5m

2) No administrator account required

3) High Performance

11. Soft Power for performance optimization

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

(2) Ability to perform analysis and architecture planning for the overall web execution environment

(3) Ability to design a proper caching strategy

(4) To further analyze the data of website performance

12. Cicatrization on 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 concerns design

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

(4) Ability to optimize code for a variety of environments to improve program execution performance

13. Determining key elements of Web performance

(1) Web Performance Optimization Foundation-http

1) HTTP is stateless

2) A Web page contains n times the HTTP request

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

1) Fiddler

2) IE10 Developer Tools

(3) Client optimization

1) Reduced number of HTTP requests

2) The bandwidth used for the download

3) The length of time the DNS query

4) The speed of CSS display

5) The speed of JavaScript calls

(4) Service-side optimization

1) IIS

Control Client

HTTP Cache Control

Control server Side

Count out Cache (Output Caching)

Improve database query speed

2) ASP. NET MVC

Call Performance Improvements

The appropriate caching policy

(5) [Seesionstate]

1) using the sessionstate property

How controller Access phase state data (Session) is controlled

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

You cannot use the CacheProfile parameter

(7) Change the default settings for Viewengine

1) Remove excess viewengine to increase the speed of resolution view

->viewengines.engines.clear ();

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

2) The order in which the view is loaded can also be changed in this way

--Default is Webformviewengine priority processing

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

(8) Avoid break-ins null to view

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

--when NULL is passed, exception is thrown, but it is try/catch out

->public Actionresultinsert () {

Return View (new products ());

}

(9) Turn off debug mode for Web. config

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

Basic knowledge of 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.