". NET" Learn ASP.

Source: Internet
Author: User

1th: Understanding Controllers and views

MVC Overview

    • The MVC principle is the framework of models, views, and controllers . (In fact, it is also a kind of thought, in order to let the front end, program, data separation, also want to achieve low coupling, high cohesion)
    • The MVC request Process is: the access controller, the controller to create the model, the model goes to the database to get the data, and the model returns to the view.
    • VS 2013 Create a MVC4 Web application that automatically generates folders for the MVC framework, respectively, model, View, Controllers
    • MVC no longer uses server controls (TextBox, GridView, etc.) to return to the HTML age, but can use the Urlhelper and HtmlHelper classes in HTML. (It's better to write back directly to the HTML code)
    • MVC no longer uses events (Page_Load ()), and returns the HTML get, post requests.

Controllers and views

    • Controller The file name must be the controller end. CCB for (ActionResult), behavior is to return data, and to process user requests
    • The view is used to display to the user interface, and the view can have a lot of behavior, you can use the controller as a class, which can write behavior and binding view . (You can also directly access the public method in the controller, is this really good or bad?) )
    • The principle of return View () is to create the Viewresult object and render the interface.
    • The method return type , in addition to ActionResult, has Contentresult (return string only), and so on.
    • Adding a declaration [nonaction]to the method header will not act as a behavior. (There are many ways to declare, for example, the behavior of a POST request, and so on, look down.) )

First MVC (actually wrote it several times before)

/controllers/usercontroller.cs

     Public class Usercontroller:controller// controller     {        public actionresult Users ( )//  behavior         {            return View ("User");   view         }    }

/views/user/users.cshtml (Right-click View () Method-add view, automatically generated)

@{    viewbag.title = "Users";} < H2 > User Information Management interface </h2>

2nd: View parameters, view using Razor syntax

Methods of transmitting parameters

    • Using viewdata[] to pass data to the page, the page can be used directly with @viewdata[].
    • In return view (), you can also pass a parameter, such as Return view ("User", userinfo), but only the reference type, not the value type.
    • Use viewbag.xxx, but cannot and viewdata[] repeat, otherwise it will overwrite viewdata[]. (Feeling ViewBag is the use of viewdata[])

Razor syntax

    • In the page with @ You can use C # code, like the <%%> in ASPX, interspersed with client and server code. (In principle, views are generally only displayed, not logic and data code)
    • Generally cshtml page, aspx and cshtml page differences and comparisons, or not very clear

/controllers/usercontroller.cs

     Public classUsercontroller:controller//Controller    {         PublicActionResult Users ()//Behavior        {            varName ="Old K"; viewdata["name1"] ="ViewData Name:"+name;//the old ViewDataViewbag.name ="viewbag Name:"+name;//The new viewbag, can take the property arbitrarily, but the performance speed is slower than ViewData.             returnView ("Users",(Object) name);//View        }    }

/views/user/users.cshtml

@{viewbag.title = "Users"; String name = (viewdata["name1"]! = NULL)? (string)    viewdata["Name1"]: "";    String viewname = (string) Model; string bagname = Viewbag.name;}<H2>User Information Management interface</H2><P>@name</P><P>@viewname</P><P>@bagname</P>
3rd article: Using EF, using server-side validation

Using EF

    • ef principle , which is entity The Framework (Entity Framework), an ORM tool (object-relational mapping), has the advantage of being easy to develop, speeding up development, and the drawback is that dealing with complex logic can be bad (perhaps some improvement).
    • ef 3 scenarios , Database auto-generation, model generation, Poco generation.
    • plus LINQ, which makes it easier to develop, so I'm also mvc + Linq to EF + jquery Combined Direction learning (there is a way to encapsulate jquery in MVC, but I feel that jquery is easy enough.)
    • vs2013 No EF Solution : I did not, read the online teaching, in C:\ProgramData\Package cache\{08aef86a-1956-4846-b906-b01350e96e30}v12.0.20912.0\ Packages\eftools, run point Repaire, if not, search the package cache for Eftools
    • Some history: EF2.0 supports EDMX generation, 4.0 supports the database first, model first, Code three modes, and 5.0 performance improvements. EF 5.0 can be used in. NET Framework4.5.

Step 1: First build the database tables, fields. (This is a traditional point method that EF can help you create.) )

Step 2: Create a folder or new item, add new item-data-ADO. NET Entity Data Model, then there is a wizard to configure the database, pull the data table in. My practice: Build an EDMX folder, build newsef.edmx (many of the configuration files inside), and also the class name to change to Newsef. (Default or entities)

Step 3: Then access the direct MVC_Web.edmx.NewsEF to invoke the Add, delete, change method, you can also use the entity class inside. (Convenient bar)

External articles: Other supplements

-General principles-

Model: Represents the business and logical layers, encapsulating the properties and methods of the entity.

View: Responsible for passing the model to the presentation layer, specifically with HTML, XML, and so on. Following the principle, the presentation layer is best not to use logic and business.

Controller: The logic of the control program, which is the tool of view and model coordination, receives the information from the view, then uploads the model, and then returns the model back to the view.

Practice Priority principle:. NET helps you build 3 of folders. Note that in the controller, the CS file name must centroller end, in views have shared (save shared view) and other files, a bit trivial, but also improve efficiency

In App_start RouteConfig.cs is the configuration route, now understood is the rule that defines the domain name, the default path is the controller name/behavior/id.

Controller

(in Conteller ActionResult method), MVC4 means what to do next, not how

There can be many types of returns:

View () returns the viewresult of views rendered

Content () returns the Contentresult of the text

File () returns files

There are JavaScript (), Json (), Httpnotfound (), Partialview () ...

Controller parameters (one of MVC's powerful features: model bindings, which can use parameters that come with a request message)

The tradition is the URL to pass the parameter, the Session, the view and so on, but this as long as has the failure parsing to run down, or through TryParse () to maintain.

The model bindings are in fact corresponding to request one by one, but the display code is omitted, and the user is easy to use:

Public ActionResult Create (string title,decimal currentprice,datetime starttime,datetime endTime)//Here is the model binding, or change to auction entity class {      var auction = new Auction (        title = Title,        currentprice = Currentprice,        StartTime = StartTime,        EndTime =

Return view () returns the parameter, such as var id = ""; Return view ("auction", id);

Razor syntax (syntax for HTML to write server code at @)

Divided into: Code Snippets and code blocks

Code snippet: such as @datetime.now or @html.actionlink ("Login")

Code block: @{

Code content

}

Variable life cycle should be page-level, it is very convenient to use.

Common features :

[HttpGet] [HttpPost] handles only get/handle post delivery mode

[AllowAnonymous] [Authorize] Call without permission validation/restriction call

[Bind (...)] The filter parameter used when the form form was submitted

[Remote ("", "")] is placed in the entity class, you can call the method to check

[HandleError (...)] exception handling, which exceptions can be specified in (), used in conjunction with the settings of Web. config

Transfer data : viewdata[] and Viewbag.xxx

Security, logging, caching

Reference:

Http://www.cnblogs.com/powertoolsteam/p/MVC_one.html

"ASP. NET MVC4 Web Programming"

". NET" Learn ASP.

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.