Initial knowledge of Ajax technology

Source: Internet
Author: User

First of all, let me explain why I need to use AJAX technology.

1. There is a text type input box on the page, and when I click Submit, I can pass the value of the text box to the background.

2. Background receive passed parameters

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

4. Re-call method to pass the return value to the front desk, the front desk directly shows what we entered

Front desk

HTML code

@model List<Mvc3demo. Models.catagory>@{viewbag.title = "catagory";}<Divstyle= "margin:50px">    <H2style= "Display:inline">category</H2>    <Selectclass= "Cata">@{//model refers to the list of classifications, traversing the list of foreach (var item in Model) {//drop-down box, name is the category name (Cata Goryname), the value is the classification number (ID)<optionvalue= "@item. ID">@item. Catagoryname</option>            }        }    </Select>    <H2style= "display:inline; margin-left:20%">Add Category</H2>    <Divstyle= "Display:inline-block">            <inputID= "Cataname"type= "text"value= "Please enter category name"onfocus= "This.value= "onblur= "if (this.value==") {this.value= ' Please enter the category name '} " />            <ahref= "javascript:void (0);"style= "height:25px"onclick= "Addcata ();">Submit</a>    </Div></Div>    
View Code

jquery Code

<script type= "Text/javascript" >functionAddcata () {//get to what we entered in the input boxvarCatagoryname = $ ("#cataName"). Val (); //Ajax's jquery statement$.ajax ({//in the form of post, as to what is different from get, I have not learned hereType: ' Post ',            //Home for the controller, Addcata for the Actionresul method in the controllerURL: "/home/addcata",            //Pass the Catagoryname as a parameterdata: {catagoryname:catagoryname},//The data type is JSON, and the controller returns not the view, but the JSONDataType: ' 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{     publicclass  catagory    {         public  Stringgetset;}          Public int Get Set ; }    }}
Model

Controller code

namespacemvc3demo.controllers{ Public classHomecontroller:controller { PublicActionResult catagory () {Service service=NewService (); //call the Getcatagory method in the service to get the taxonomy listlist<catagory> list =service.            Getcatagory (); //back to view            returnView (list); }                PublicActionResult Addcata (stringcatagoryname) {Service service=NewService (); //call the Addcatagorys method and add the data inservice.            Addcatagorys (Catagoryname); //call the Getcatas method again to get to the category listlist<catagory> list =service.            Getcatagories (); //find the last category in the Category list, which is the category you just addedCatagory catagory = list[list. Count-1]; //return JSON            returnJson (catagory); }     }}
Controller

Content in the service class file

namespacemvc3demo.bll{ Public classService () {/// <summary>        ///querying a categorized list from a database/// </summary>        /// <returns>Category List</returns>         PublicList<catagory>getcatagories () {stringMyConn ="server= server name; uid=sa;pwd= password; database= database name";//Connection Database String            using(SqlConnection myconnection =NewSqlConnection (myconn))//Define a data connection instance{myconnection.open ();//Open Connection                stringMyselect ="Select ID, catagoryname from dbo. Catagorys;";//querying IDs and Catagoryname SQL statements from the Catagorys tableSqlCommand mycommand =NewSqlCommand (Myselect, MyConnection);//Instance a database directiveDataSet ds =NewDataSet ();//creates a new instance of the DataSet table,SqlDataAdapter adapter =NewSqlDataAdapter (MyCommand);//creates a new instance of the SqlDataAdapter fill with parameters,Adapter. Fill (DS);//Populating table DS with Datalist<catagory> list =NewList<catagory> ();//instantiate a list of classifications                if(ds. Tables! =NULL&& ds. Tables.count >0)//The judgment table is not empty, and the number of tables is greater than 0{DataTable dt= ds. tables[0];//take the first sheet                    if(dt! =NULL&& dt. Rows! =NULL&& dt. Rows.Count >0)//To determine that the first table is not empty, and that the table row is not empty, the number of table rows is not empty                    {                        foreach(DataRow rowinchDt. Rows)//Traverse table each row                        {                            ObjectObjId = row["ID"];//ObjID the ID in the storage database                            intid = dataconvert.toint32 (objId);//convert ObjID to int type, stored in ID                            Objectobjname = row["Catagoryname"];//objname storing Catagoryname in the database                            stringName =string. Empty;//declares a name empty                            if(objname = =NULL)//judge objname to be empty                                Continue;//jump out of this cycleName = Objname.tostring ();//convert objname to String typeList. ADD (NewCatagory () {id = id, catagoryname = name});//Add the ID and name to the category list                        }                    }                }                returnList//Return to Category list            }        }                /// <summary>        ///adding data to a database/// </summary>        /// <param name= "Catagoryname" >category names added to the page</param>        /// <returns>success or not</returns>         Public BOOLAddcatagorys (stringcatagoryname) {            stringMyConn ="server= server name; uid=sa;pwd= password; database= database name";//Connection Database String            using(SqlConnection myconnection =NewSqlConnection (myconn))//Define a data connection instance{myconnection.open ();//Open Connection                stringMyinsert ="INSERT INTO dbo. Catagorys values (@catagoryName);";//to add a taxonomy to a database Catagorys tableSqlCommand mycommand =NewSqlCommand (Myinsert, MyConnection);//Instance a database directiveMYCOMMAND.PARAMETERS.ADD (NewSqlParameter () {parametername ="Catagoryname", Value = Catagoryname});//ways to add a parameter collection                Try//Exception Handling                {                    inti = Mycommand.executenonquery ();//executes the database, returning the number of rows affected                    if(I >0)                    {                        return true; }                    return false; }                Catch(Exception ex) {return false; }            }        }    }}
Service

The design of the database is the self-growing ID int type as the primary key, Catagoryname is the varchar (50) type

1. Obtain the classified data from the database, the catagory action in the background controller invokes the Getcatagory method in the service, returns a list, which is a list of categories, through the return View (list Return the list as a parameter to the page, the front page of the first line of HTML @model list<mvc3demo.models.catagory> means that we can directly access the controller in a strong type passed through the list of categories.

2. Add classification information to the database, click Submit on the Web page, have an onclick event, execute the Addcata method, and pass var catagoryname = $ ("#cataName"). Val (); Gets the value entered and then uses AJAX technology, Pass the Catagoryname as a parameter to the background (POST), execute the Addcata action in the home controller, this action invokes the Addcatagorys method in the service, Of course this Addcatagorys method again affects the number of rows >1 (SQL statement execution succeeds) returns a true, and then addcata the action, we call the Getcatagory method again, get to the classification, The last category is the category we just added, which is list[list.count-1], and then we return to JSON and pass the last category of the parameter to the foreground return JSON (catagory).

3. The foreground receives the data passed from the background after datainfo, then adds the new classification (Jquer Append method) After the element with the class name Cata, and can also set the newly added category to selected (select event selected)

Note: This essay is only for reference use, but also has a lot of small flaws, the most important is not the code, logic is the most significant.

Initial knowledge of Ajax technology

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.