First understanding of ajax technology, first understanding of ajax

Source: Internet
Author: User

First understanding of ajax technology, first understanding of ajax

First, let me introduce why I need ajax technology.

1. There is a text input box on the page. When I click Submit, I can pass the value in the text box to the background.

2. parameters received in the background

3. Connect to the database and add the passed content to the database.

4. Call the method to pass the returned value to the foreground. The foreground displays the input content directly.

 

Front-end

Html code

@ Model List <Mvc3Demo. models. catagory >@{ ViewBag. title = "Catagory" ;}< div style = "margin: 50px"> 

View Code

Jquery code

<Script type = "text/javascript"> function addcata () {// obtain the content input in the input box var catagoryname =$ ("# cataName "). val (); // jquery declaration of ajax $. ajax ({// transmitted in the form of post. As for the difference with get, I haven't learned the type: 'post' here, // Home is the controller, addCata is the ActionResul Method url in the Controller: "/Home/AddCata", // pass catagoryname as a parameter data: {catagoryname: catagoryname}, // the data type is json, the returned result in the controller is not a view, but a json ype: 'json', success: function (dataInfo) {$ (". cata "). append ("<option value = '" + dataInfo. ID + "'>" + dataInfo. catagoryName + "</option>"); $ (". cata "). find ("option [value = '" + dataInfo. ID + "']"). attr ("selected", "selected") ;}}}</script>
View Code

Background

Medol code

namespace Mvc3Demo.Models{     public class Catagory    {        public string CatagoryName { get; set; }        public int ID { get; set; }    }}
Model

Controller code

Namespace Mvc3Demo. controllers {public class HomeController: Controller {public ActionResult Catagory () {Service service = new Service (); // call the GetCatagory method in Service, obtain the category List <Catagory> list = service. getCatagory (); // return to the View return View (list);} public ActionResult AddCata (string catagoryname) {Service service = new Service (); // call the AddCatagorys method, add data to the service. addCatagorys (catagoryname); // call the GetCatas method to obtain the category List <Catagory> list = service. getCatagories (); // locate the last category in the category list, that is, the newly added category Catagory catagory = list [list. count-1]; // return Json (catagory );}}}
Controller

Service file content

Namespace Mvc3Demo. bll {public class Service () {// <summary> /// query the category List from the database /// </summary> /// <returns> category List </returns> public List <Catagory> GetCatagories () {string myConn = "server = server name; uid = sa; pwd = password; database = database name"; // Connection database string using (SqlConnection myConnection = new SqlConnection (myConn )) // define a data connection instance {myConnection. open (); // Open the connection string mySelect = "select id, catagoryName from dbo. catagorys; "; // from SqlCommand myCommand = new SqlCommand (mySelect, myConnection) for querying the id and catagoryName in the Catagorys table; // instance a database command DataSet ds = new DataSet (); // create a new instance of the DataSet table, SqlDataAdapter adapter = new SqlDataAdapter (myCommand); // create a new instance filled with SqlDataAdapter, with parameters, adapter. fill (ds); // Fill the data in the ds List <Catagory> list = new List <Catagory> (); // instantiate a category List if (ds. tables! = Null & ds. tables. count> 0) // judge whether the table is not empty and the number of tables is greater than 0 {DataTable dt = ds. tables [0]; // obtain the first table if (dt! = Null & dt. Rows! = Null & dt. rows. count> 0) // judge whether the first table is not empty, the table row is not empty, and the number of table rows is not empty {foreach (DataRow row in dt. rows) // traverse each row of the table {object objId = row ["id"]; // The id int id of the objId stored in the database = DataConvert. toInt32 (objId); // convert the objId to the int type and store it in the id object objName = row ["catagoryName"]; // The objName stores the catagoryName string name = string in the database. empty; // declare a name to be Empty if (objName = null) // judge whether objName is null continue; // jump out of this loop name = objName. toString (); // convert objName to string type list. add (new Catagory () {ID = id, CatagoryName = name}); // Add the id and name to the category list }}} return list; // return to the category list }}/// <summary> /// add data to the database /// </summary> /// add on the <param name = "catagoryname"> page </param> /// <returns> success or not </returns> public bool AddCatagorys (string catagoryname) {string myConn = "server = server name; uid = sa; pwd = password; database = database name"; // Connection database string using (SqlConnection myConnection = new SqlConnection (myConn )) // define a data connection instance {myConnection. open (); // Open the connection string myInsert = "insert into dbo. catagorys values (@ catagoryName); "; // Add SqlCommand myCommand = new SqlCommand (myInsert, myConnection) to the database Catagorys table; // an instance of a Database Command myCommand. parameters. add (new SqlParameter () {ParameterName = "catagoryName", Value = catagoryname}); // Method for adding a parameter set try // Exception Handling {int I = myCommand. executeNonQuery (); // execute the database and return the affected rows if (I> 0) {return true;} return false;} catch (Exception ex) {return false ;}}}}}
Service

The database is designed as the auto-increment id int type of the primary key, and catagoryName is of the varchar (50) type.

 

1. obtain the category data information from the database. The Catagory Action in the background Controller calls the GetCatagory method in the Service and returns a list, which is the category list) return list to the page as a parameter. @ model List <Mvc3Demo In the first line of html on the foreground page. models. catagory> this means that we can directly access the category list passed by the strong type in the Controller.

2. add category information to the database. Click Submit on the webpage. There is an onclick event. Execute the addcata method and use var catagoryname = $ ("# cataName "). val (); get the input value, and then use ajax technology to pass the catagoryname as a parameter to the background (post), and execute the AddCata Action in the Home controller, this Action calls the AddCatagorys method in the Service. Of course, if the number of rows affected by the AddCatagorys method is greater than 1 (the SQL statement is executed successfully), a true value is returned, and then AddCata's Action is returned, we call the GetCatagory method again to obtain the category. The last category is the category we just added, that is, list [list. count-1], return json, and pass the final classification of the parameter to the front-end return Json (catagory ).

3. after receiving the data transmitted from the background dataInfo, the foreground adds a new category (jquer append method) after the element named cata, you can also set the newly added category to select (select selected event)

 

Note: This article is for reference only. It also has many flaws. The most important thing is not code, but logic.

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.