ASP. NET -- NVelocity (2), asp. netnvelocity

Source: Internet
Author: User

ASP. NET -- NVelocity (2), asp. netnvelocity

In the previous lesson, we talked about the simple application of NVelocity, but we didn't deal with the database. This time, we came to the database connection to implement the addition, deletion, modification, and query of personnel.

1. Review of the previous blog

Link: http://blog.csdn.net/u010955843/article/details/42528761

Before starting the lecture, let's review the content of the previous lesson. There are two main pages: one is the page of the general processing program, and the other is the rendered template.

Ø Mechanism

In the previous blog, we created a person class, assigned a value to it in a general processing program, and then handed it to the template (html) for data filling and rendering it into an html page, the generated plain html text is returned to the general handler, and the general handler returns it to the browser for resolution and display.

Benefits

The separation of data and logic from the interface is realized: The data is given to the template (generally taken by html), and the general processing program gets the rendered html for output. The template no matter the data source, only know how many rows and columns need to be set in the table. Generally, the processing program only retrieves data and passes it to the template. No matter what the template will render the data, that is, you can simply take care of your own parts.

2. Connect to the database to add, delete, modify, and query personnel

In the previous lesson, we only wrote data source objects in general processing programs. So how to develop NVelocity in traditional web to interact with databases? Let's first introduce the procedure of programming.

Create a database and a table

You can set it by yourself. Our database is CRUDTest, which indicates Persons.


Set Id to auto-increment. We can manually enter several records

Ø CommonHelper

Like the previous one, we first download the NVelocity DLL, add it to the created Project, drag it directly under the project, and then add a reference to it.

We wrote the template in a general processing program last time, but we know that this is only applicable to one or a few processing programs. If we want to reuse or use the template conveniently, we can encapsulate it and put it into a class, which achieves method reuse.

We know that there are only two parameters that are different here: the template to be rendered, and the file or data to be filled with the template.

The Code is as follows:

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> using NVelocity; using NVelocity. app; using NVelocity. runtime; using System. collections. generic; using System. linq; using System. web; // using NVelocity; using NVelocity. app; using NVelocity. runtime; the required // class is used to encapsulate the rendering namespace yinqingmuban {public class commonHelper {// <summary> // use data to fill the templateName template, rendering generate html return /// </Summary> /// <param name = "templateName"> Template name </param> /// <param name = "data"> Fill in template data </ param> // <returns> </returns> public static string RenderHtml (string templateName, object data) {VelocityEngine vltEngine = new VelocityEngine (); vltEngine. setProperty (RuntimeConstants. RESOURCE_LOADER, "file"); vltEngine. setProperty (RuntimeConstants. FILE_RESOURCE_LOADER_PATH, System. web. hosting. hostingEnvi Ronment. MapPath ("~ /Templates "); // The folder where the template file is located. We followed the previous lecture and placed it in the templates folder. You can also create vltEngine with another name. init (); // The engine initializes VelocityContext vltContext = new VelocityContext (); vltContext. put ("Data", data); // you can use $ data in the Template to reference Template vltTemplate = vltEngine. getTemplate (templateName); // rendered html template System. IO. stringWriter vltWriter = new System. IO. stringWriter (); vltTemplate. merge (vltContext, vltWriter); string html = vltWriter. getStringBuilder (). toString (); return html ;}}</span> </strong>
Ø Sqlhelper

I believe everyone has learned three layers, so I will not introduce them too much here. It encapsulates a series of addition, deletion, modification, and query methods, and establishes connections in the database. It is not shown here

Ø configuration file

It is used to configure the string used to connect to the database, so that we can flexibly change the database, instead of changing the code.

<strong><span style="font-family:Microsoft YaHei;font-size:14px;"><connectionStrings>  <add name="conStr" connectionString="data source=.;database=CRUDTest;uid=sa;pwd=123456;"/></connectionStrings></span></strong>

General handler displayed by personnel (personlist. ashx)

Here we mainly read the data and render it to the html page for output.

<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> using System; using System. collections. generic; using System. linq; using System. web; using System. data; namespace yinqingmuban {// <summary> // summary of the personlist /// </summary> public class personlist: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; // context. response. write ("Hello World"); DataTable dt = sqlHelper. executeDataTable ("select * from Persons"); // The DataTable is not a set, so the foreach cannot be traversed. The Rows attribute of the DataTable // represents the set of data Rows in the table (the set of DataRow ), generally, pass the DataRowCollection // to the template to easily traverse string html = commonHelper. renderHtml ("personlist.html", dt. rows); context. response. write (html) ;}public bool IsReusable {get {return false ;}}</span> </strong>

Creation of an employee's profile template (personlist.html)
<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <! DOCTYPE html> 

Add, delete, and modify the list (personEdit. ashx)
<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> using System; using System. collections. generic; using System. linq; using System. web; using System. data. sqlClient; using System. data; namespace yinqingmuban {// <summary> // summary of personEdit /// </summary> public class personEdit: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html "; // PersonEdit. ashx? Action = AddNew // PersonEdit. ashx? Action = Edit & Id = 3 string action = context. request ["action"]; if (action = "AddNew") {// you can determine whether the Request contains a Save statement and the value is true, if yes, it indicates that bool save = Convert is requested by clicking save. toBoolean (context. request ["Save"]); if (save) // Yes Save {string name = context. request ["Name"]; int age = Convert. toInt32 (context. request ["Age"]); string email = context. request ["Email"]; sqlHelper. executeNonQuery ("Insert into Persons (Name, Age, Email) value S (@ Name, @ Age, @ Email) ", new SqlParameter (" @ Name ", name), new SqlParameter (" @ Age ", age ), new SqlParameter ("@ Email", email); context. response. redirect ("personlist. ashx "); // return to the List page after saving successfully} else {// string html = CommonHelper. renderHtml ("PersonEdit.htm", new {Name = "", Age = 20, Email = "@ rupeng.com"}); // defines the Action of an anonymous object, which may be the same as the field in the database, we recommend that you separate related and irrelevant fields. A New anonymous type is equivalent to creating another anonymous class in an anonymous class. var data = new {Action =" AddNew ", Person = new {Name =" ", Age = 20, Email =" @ rupeng.com "}}; // render string html = commonHelper. renderHtml ("personEdit.html", data); context. response. write (html) ;}} else if (action = "Edit") {// you can determine whether Save is contained and True, if yes, click the save button bool save = Convert. toBoolean (context. request ["Save"]); if (save) {// do not remember all the information on the server side. Try to pass the information through the client. // the server is a amnesia (stateless ), the server only recognizes the information in the Request long id = Convert. toInt64 (co Ntext. request ["Id"]); string name = context. request ["Name"]; int age = Convert. toInt32 (context. request ["Age"]); string email = context. request ["Email"]; sqlHelper. executeNonQuery ("update Persons set Name = @ Name, Age = @ Age, Email = @ Email where Id = @ Id", new SqlParameter ("@ Id", id ), new SqlParameter ("@ Name", name), new SqlParameter ("@ Age", age), new SqlParameter ("@ Email", email); context. response. redirec T ("personlist. ashx ");} else {long id = Convert. toInt64 (context. request ["Id"]); DataTable dt = sqlHelper. executeDataTable ("select * from Persons where Id = @ Id", new SqlParameter ("@ Id", id); if (dt. rows. count <= 0) {context. response. write ("data with Id =" + id + "not found");} else if (dt. rows. count> 1) {context. response. write ("find multiple data records with Id =" + id + ");} else {DataRow row = dt. rows [0]; var data = new {Act Ion = "Edit", Person = row}; string html = commonHelper. renderHtml ("personEdit.html", data); context. response. write (html) ;}} else if (action = "Delete") {long id = Convert. toInt64 (context. request ["Id"]); sqlHelper. executeNonQuery ("delete from Persons where Id = @ Id", new SqlParameter ("@ Id", id); context. response. redirect ("personlist. ashx ");} else {context. response. write ("Action parameter error! ") ;}} Public bool IsReusable {get {return false ;}}</span> </strong>

Creation and deletion of custom templates (personedit.html)
<Strong> <span style = "font-family: Microsoft YaHei; font-size: 14px;"> <! DOCTYPE html> Ø Effect
List display

Click Add person

Click to edit

By hiding fields to achieve the desired results, we use hidden fields on the page for addition, deletion, and modification. The hidden fields are server-side controls, in this way, the server can obtain the corresponding value by hiding the name of the field, mainly because some operations are not visible to the user, but only to be seen by the program, therefore, a hidden field is created.

So far, we can interact with the database. You can write code to see the effect.

3. Summary

This is perfect. Otherwise, I always feel that something is missing. I have been busy recently and have never written this blog about database interaction. In mvc, there is also an engine Razor, we call it a view engine. We hope that the foundation of this blog will arouse your curiosity about engine exploration. Let's go and study it on your own. I believe you will be interested.


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.