mvc_ first pass _ the business logic and model

The methods of dynamic web objects:

  Before we mentioned, the object can be obtained using the request and the user requests a series of related information. In this section, we look at two other commonly used general-purpose objects.

  response object: to respond to customers. The most common usage is similar

    “Response.Redirect("/Home/Index1");”

    It represents the user's browser to jump to the current site "/ Home / Index1" position.

    Commonly used in a variety of errors occur when the early termination of the current process.

  Session object: ViewData and usage of similar, but also to store data dictionary mode. example:

    Session [ "hello"] = "Hello";

    This variable is valid for the "current session" can also be understood as "this visit." In general, the user exits the site, or no operation within 20 minutes, "current session" was over.

    Each user can have a set of Session variables of their own, are not in conflict with each other, across the controller and action to pass a value.

    Based on this, it is usually used to store user information across the whole station. Such as user name, permission levels, avatars and so on.

 

  Example: complete a login procedure, enter a user name, password, login successfully entered operation page; otherwise enter the wrong page. The page displays the current user name.

    Controller code:    

public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index(string u="0",string p="0")
        {
            Session["user"] = u;
            if(u == "123" && p == "456")
            {
                Response.Redirect("home/get_menu");
            }
            else if(u != "0" && p != "0")
            {
                Response.Redirect("/home/wrong");
            }
            return View();
        }
        public ActionResult get_Menu()
        {
            return View();
        }
        public ActionResult Wrong()
        {
            return View();
        }
    }

    Log in view code:      

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <form>
            用户名:<input type="text" name="u" /><br />
            密码:<input type="password" name="p" /><br />
            <input type="submit" value="登录" />
        </form>
    </div>
</body>
</html>

      Log in view of the success of the code:

@ { 
    Layout = null ; 
}

 <DOCTYPE HTML!> 

<HTML> 
<head> 
    <Meta name = " the viewport " Content = " width = Device-width " /> 
    <title> get_Menu </ title> 
</ head> 
<body > 
    <div>  
        current user @ (the Session [ " the user " ] .ToString ()) <br /> 
        logged, where the operation menu should appear. . . . 
    </ div> 
</ body> 
</ HTML>

      Login failed view code:

@ { 
    Layout = null ; 
}

 <DOCTYPE HTML!> 

<HTML> 
<head> 
    <Meta name = " the viewport " Content = " width = Device-width " /> 
    <title> Wrong </ title> 
</ head> 
<body > 
    <div> 
        current user @ (the Session [ " the user " ] .ToString ()) <br /> 
        Login failed for user name, password is incorrect. 
    </ div> 
</ body> 
</ HTML>

 

Yewuluojiceng

  This layer, in many textbooks mvc's not reflected, there are a lot of people classify it in the category of "controller." My own understanding is: a controller simply scheduling, and business logic is between scheduling and operations between the read and write data, worth up another one to write.

  "Triangle" exercises in the previous chapter, the controller is responsible for input according to the number of layers, the content is calculated Triangle, and then return to the view, there is a little confusion. We try to change the wording. The following belong to my personal habits, for your reference.

  In the project, create a new folder "functions", expressed kitchen, complete all business processes. In which a new category, "yanghui.cs" to complete the generation of Pascal's triangle, as shown below:

  new folder:

  

  New categories:

  

  Select the type of class, name yanghui:

  This class is the main function according to the input number of layers, the calculation is completed Triangle. Therefore, this operation can be written in its static method (without instantiation can call)

  code show as below:  

public class Yanghui
    {
        public static int[,] get_Yanghui(int n)
        {
            int[,] a;
            a = new int[n, n];
            for (int i = 0; i < n; i++)
            {
                a[i, 0] = 1;
            }
            for (int i = 1; i < n; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    a[i, j] = a[i - 1, j - 1] + a[i - 1, j];
                }
            }
            return a;
        }
    }

  The controller simplifies to:

public ActionResult Index(int n=0)
        {
            if (n == 0)
            {
                ViewData["d1"] = null;
            }
            else
            {
                ViewData["d1"] = Yanghui.get_Yanghui(n);
            }
            return View();
        }

  Do not forget to introduce namespaces business logic resides in the head controller file:

using WebApplication1.functions;

  Such controllers, it looks like the boss, the way only responsible for scheduling. Projects more clear.

  Namely: according to input parameters, to decide what to send kitchen working and what to take to the customer directly to the waiter.

  View code unchanged, the effect of the implementation of the program is not changed, but the whole procedure more clear and smooth.

model:

  Intuitive understanding:

    Courses on a controller and a view of the end, everyone left a complete student data CRUD smaller jobs. At that time, we have focused on the program logic controller.

    Now we can look back and think, how the program should layout. Since the entire article is a basic operation of the database, the use of "Kitchen", is not it feel a little less right.

    For this "manual labor", we can introduce a new module to handle ---- model.

    That example, all operations are on the "student" data is completed. "Student" and became a frequent part of the database interaction. It is on the one hand to keep the database deal, on the other hand need to intersect with the program. Like a nail embedded in objects in part to the tip, it is struck in part to the flat.

    Model as well. It is responsible for dealing with the database, and then with it, the program would not go inside the vault ...... even do not control logic library (of course, when writing these models have tubes); on the other hand, it must be the "kitchen "and" the boss "provides a good method to use. We usually use the model class to complete the work.

    The following code can be used as a model in the examples which:

class Student 
    { 
        String the above mentioned id, XM, NL, ZY, SQL; // SQL is a record ready to perform the action statements 
        public Student ( String input_id) // constructor 1, only initialization number, apparently ready to remove your 
        { 
            the above mentioned id = input_id ; 
        } 
        public Student ( String input_xm, String input_nl, String input_zy) // constructor 2, not numbered, evidently put themselves into the table 
        { 
            XM = input_xm; 
            NL = input_nl; 
            ZY = input_zy; 
        }
        public Student ( String input_id, String input_xm, String input_nl, String input_zy) // constructor 3, and consequently there is, for updating 
        { 
            ID = input_id; 
            XM = input_xm; 
            NL = input_nl; 
            ZY = input_zy; 
        } 
        public  void insert_it ( ) // inserting method 
        { 
            SQL = " iNSERT INTO XS (XM, NL, ZY) values ( ' " + XM + " ', "+nl+",'"+zy+"')";
            Hc_db.do_nonquery(sql);
        }
        public void modify_it()//修改方法
        {
            sql = "update xs set xm='"+xm+"',nl="+nl+",zy='"+zy+"' where id="+id;
            Hc_db.do_nonquery(sql);
                {Delete method//delete_it ()voidPublic 
        }
=
            SQL"delete from xs where id=" + id;
            Hc_db.do_nonquery(sql);
        }
    }

    Once you have the Student class (model) this tool, the controller only needs to receive operating data and requests, new a specific "student" the object out, it can directly operate. A bit like guests only ordered a glass of water, the boss can draw water directly to the servant served just fine.

    For example, the process controller code is substantially removed (not rigorous, for reference only):

public ActionResult Index(string stu_id)
        {
            Student stu = new Student(stu_id);
            stu.delete_it();
            return View();
        }

    P41 turn on the book

    Please follow this logic, forget the above code, write their own set of student information management program (MVC taste)

Small Exercises:

    The above example, if the business logic of these operations is more complex (for example, before deleting the students need to determine the eligibility of student achievement, adequacy of operator privileges, etc.), directly to the "kitchen" implementation.

    Prior knowledge of reference on this idea and, with permission to write a set of management on the basis of the above example the student information management procedures. It reads as follows:

      1, the site start page displays all student information.

      2, site users classified as "not logged in", "Normal", "administrator" three levels.

      3, the unregistered users can only view information for all students.

      4, the average user can query the specified student information, add new students.

      5, administrators can modify, delete student information.

Guess you like

Origin www.cnblogs.com/wanjinliu/p/11519024.html