003.MVC Controller and data transfer

Source: Internet
Author: User

I. Controller Basics

What is a controller?
Controllers generally inherit from System.Web.Mvc.Controller

Controller class:
1. A single controller can contain multiple methods (action: Action/method)
2. method to get input data from the request
3. Process and retrieve or update model objects in the database
4. Method output result, can be a view or a jump
5. The Controller method performs processing with the passed-in parameter values and retrieves or updates the model objects in the database. Then, a view is selected to display

Method response Output (The purpose of the study: To solve practical problems, to implement arbitrary selection of views, arbitrary jump (redirection))

The controller's method usually generates a response to the client when the request is processed
Most methods return instances of the ActionResult class or other derived classes.
You can return an object of any type, such as a string, Integer, or boolean value.
These return types are wrapped in the appropriate actionresult type before rendering to the response stream
1.ViewResult, equivalent to returning a view page
2.RedirectResult. Jump to the specified URL

Use of the Controller
Output of the method
Conclusion: return type ActionResult
Four common methods of return
View ()
Redirect ()
Redirecttoaction ()
Redirecttoroute ()

public class Homecontroller:controller

Public ActionResult Index ()
return view ()//A view with the same name as the method name in the same controller
Return view ("~/views/studeny/index.cshtml");//view of different controllers, rarely used
Return view ("Index2");//view with a different name in the same controller and the method name

Redirect ("/studeny/index");//views of different controllers, commonly used
Redirecttoaction ("Index", "Studeny")
Return Redirecttoroute (New {Controller = "studeny", action = "Index"});

Purpose of the study: solving practical problems
Implement any selected view, any jump (redirect)

A comparison of 4 methods used in return
Conclusion 1:
1> different views of the same controller view
Sometimes it is possible to enter a different controller view with less
Features: Direct access to the view from the controller c>>v
2> view of different controllers best with redirect? Series method
Features: C>>c? F?>>v?
Conclusion 2:
Enter a different controller view
View c1>>v? Go straight home.
Redirect? C1>>c? F?>>v? Go to the supermarket home
Conclusion 3:
Redirect? Three methods The basic functions are the same. Parameter filling style is different
Note: Different views of the same controller, sometimes with redirect?

Exercise: Define a method that implements
1> Enter User Login page
2> access to the front desk subject to page
3> into the background first page

--------------------------------------------------------------------------------------------------------------- -----------------
Two. The ASP. NET MVC application is highly dependent on the contract (default configuration)

-Convention simplifies communication (improves development efficiency)

Named in ASP. NET MVC:

1. Named by convention. Includes the following:
A. Name of controller, must end with "controller"
such as: Homecontroller,admincontroller
B. When referencing a controller, simply specify the previous name
such as: Home,admin
C. Controllers should be placed in the Controller directory
D. Views and partial views should be placed in the "view" directory
such as: HomeController corresponding to "/view/home"
E. Layout page should start with "_" and put in "/view/shared" directory

2. customizing

ASP. NET MVC Project type
1. Empty site templates
folder + files
Contains the fewest directories and files
The "Use HTML5 semantic tagging" option indicates that Visual Studio begins to support HTML5 markup.
Razor view engine is a new view engine for ASP.
2.Internet (Internet) template
Folder + file + Portal file
(Required files for login registration function, form authentication)
3.Intranet (Local area network) templates
Folder + file + Portal file
(Files required for Windows authentication)
The application contains more portal files

_viewstart.cshtml: View starts when judging views with no master page
Global.asax: Specifies the routing
_layout.cshtml: Master Page
Error.cshtml: Error page
SITE.CSS: Style (can be added or modified)
Two. Structure of the site [project folder and the composition of the file]
Three. Global configuration file
Global.asax Global configuration file, path configuration for the entire MVC application
Routing: ASP-specific URLs
Routing rules (URL pattern) = Routing rules:
Controller action Method parameters
How to work: Browser url>> framework parsing, finding >> controllers and methods

--------------------------------------------------------------------------------------------------------------- -----------------
Three. Passing data between methods and views

Value of method to view

Two methods:

Method One: Viewbag/viewdata
Method Two: Model (models)

Method One:
There is not much difference in use, the wording is different!

ViewData 1.0 Manual Conversion
ViewBag 3.0 easy to use (like to use) automatic conversion performance slightly lower

Different types:
Dynamic type, dictionary type, commonly used to pass a small number of values, you can also transfer a large number of complex values

Passing Data using Viewbag/viewdata

Controller code:
Public ActionResult Index ()
String a = "123";
viewdata["x"] = A;
String date = DateTime.Now.ToString ();
VIEWBAG.A = date;
viewdata["Y"] = date;
return View ();
View Code:
@ViewBag. x<br/>
@ViewData ["x"]<br/>
@ViewBag. a<br/>
@ViewData ["Y"]

Method Two: * * * *
Model method used more!!
Simple types, complex types such as: Dataset,datareader

Data types that can encapsulate data, or data types that can interact with a data source (database)
Model objects are instances of classes that encapsulate data

form of expression:
int i=0;
String S= "";
Built-in Custom
Int,int[]; Student,user
Student[] List<student>
form of expression:
A class:
Model folder: Data type >> class
Requirements: Student Information management
1>student Class: Field Id,name,tel
Method Insert,delete
Two classes:
2>student class: Field Id,name,tel is often called entity class
SqlHelper class: Method Insert,delete is often called a data access class
Three classes:
3>student class: Field Id,name,tel entity class
Studentdal class: Method Insert,delet E Entity Access class
Insert (Student Stu)
SqlHelper class: Method Insert,delete data Access Class
Insert (String sql)

Application Examples:

1) Use models to pass simple data

2) Passing custom objects using models
Step 1: Create the model. Compile [Regenerate]
Step 2: Create a Controller, method, add view
Note: Add view, select (Create strongly typed view)
Contains @model Day02mvcmodel pass data. Models. Entity class Statement view, called strongly typed view [strongly typed model declared in view]
Benefits 1:model has a hint function
Benefit 2: A view can use a strongly typed HTML helper method

Controller code:
Using Day02mvcmodel to pass data. Models;
Public ActionResult Index ()
Student stu = new Student
Name= "Zhang San",
sex= "Male"

Return View (STU);
View Code:
@Model. Name
@Model. Age
@Model. Sex
Model entity Class Code:
public class Student
public string Name {get; set;}
public int Age {get; set;}
public string Sex {get; set;}

3) using the model to pass an array of custom objects (collections)
Step 1: Create the model. Compile [Regenerate]
Step 2: Create a controller, method, implement method to return multiple objects
Step 3: Add a view, select (Create strongly typed view)
Note: Return multiple objects, modify [email protected], as below, @model Ienumerable<day02mvcmodel pass Data .models.student>
Step 4: Show in view, note: Return multiple objects, display with @foreach

Controller code:
Using Day02mvcmodel to pass data. Models;
Public ActionResult Index ()
Student stu = new Student
Name= "Zhang San",
sex= "Male"

Return View (STU);
Public ActionResult Index2 ()
list<student> list = new list<student>{
New Student{name= "Zhangsan", age=18, sex= "Male"},
New student{Name= "Lisi", age=25,sex= "female"}

return View (list);


View Code:
@model Ienumerable<day02mvcmodel Pass Data .models.student>
@foreach (var a in Model)

Model entity Class Code:
public class Student
public string Name {get; set;}
public int Age {get; set;}
public string Sex {get; set;}

Use the model to return multiple objects to import a model's namespace into the view

1. Using a using statement to introduce
@using Day02mvcmodel pass data. Models;
@model Student

2. Add a namespace import in the Web. config file
<add namespace= "Day02mvcmodel pass Data"/>
<add namespace= "System.Web.Helpers"/>
<add namespace= "SYSTEM.WEB.MVC"/>
<add namespace= "System.Web.Mvc.Ajax"/>
<add namespace= "System.Web.Mvc.Html"/>
<add namespace= "System.Web.Routing"/>
<add namespace= "System.Web.WebPages"/>

3. Strongly typed model in the view
@model Day02mvcmodel pass data. models.student
@model Student
@model ienumerable<student>

003.MVC Controller and data transfer

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.