Based on Ajax form submission and simple background processing applications, ajax form submission background

Source: Internet
Author: User

Based on Ajax form submission and simple background processing applications, ajax form submission background

First, let's start with form submission. To submit a form, we need to collect the form data first (as for verification, I will not talk about it, but leave it for the next time ), with jquery, it is still simple to get an html value $ ("xxid "). val () and so on, but if a form collects a lot of data and there are many forms like this, it will be difficult to use this method, and it is easy to get errors. Therefore, we can simply define a collection rule. For example, we can mark the Data Form Control to be uploaded back to the server, then, the marked data will be taken back together.

Take the simplest style input as an example. <input type = "text" id = "txtcode" name = "txtcode" datafield = "Code" style = "width: 200px "/> we add a" datafield "attribute, and the saved value is the attribute name of the corresponding server-related class. With this mark, the front-end can fetch data.

We can set a general method, as shown in the following code:

GetFormData: function (formid) {var data ={}; // get the TEXT file content $ ("#" + formid + "input [type = text]"). each (function (I, o) {var jo = $ (o); if (jo. attr ("datafield") {var str = jo. val (); str = str. replace ("", ""); if (str! = "") {Data [jo. attr ("datafield")] = jo. val () ;}}); return data ;}

Here is a simple way to get all the text in the form and put it into a data object. As for how to obtain the value of other form controls, I will not talk about it. The principle is similar.

The next step is to send the data to the server. I will use ajax with jquery directly here.

Var save = function (sender) {$ (sender ). prop ("disabled", true); // disable the button to prevent repeated transmission of var data = getFormData ("form1"); var jsonobj = {jsondata: data }; var textdata = JSON. stringify (jsonobj); $. ajax ({type: "POST", contentType: "application/json; charset = UTF-8", url: "xxxxx. aspx/Save ", dataType:" json ", data: textdata, success: function (msg) {if (msg. d = "1") {document. form1.reset (); alert ("saved successfully! ");} Else if (msg. d =" 0 ") {alert (" Saving failed! ") ;}}, Complete: function (jqXHR, textStatus) {$ (sender). prop (" disabled ", false); // restore button }});}

Here, "xxxxx. aspx/Save" is the ajax processing page, and the other is a webmethod. We have done a bit to prevent the customer from processing too quickly, Service Processing too slowly, and repeated clicks.

This form data collection completes the return to the server. Here, the JSON. stringify method of json2.js is used to convert an object to a json character. The advantage is that you do not have to consider the json format for the json string, which is simple and clean.

Then the customer has included the data, and the server should also process the data. The data key (json key) we used in the past cannot all include all attributes of a data class. There are also many data classes. Which class should be known only to the server. So here we need to write a helper conversion class. There is another problem here. There may be many data classes. Isn't it a pitfall to write a method for each class? Therefore, we analyze the data format transmitted from the client to the server. It is a set of key-value pairs and will not be repeated, so it is equivalent to a Dictionary <string, string>, there are many classes in the background, so we can determine at least one input parameter, and the outgoing class is the relevant class. Related classes? Which type of data is available only in the specific background collection method. Now we have a Dictionary <string, string> to be converted into a data class. What are the attributes of the Data class? But the key (key) of the Dictionary <string, string> can be considered as a subset of this data class attribute set, and the value (value) of this Dictionary <string, string>) is a subset of the Data class attribute value toString. That would make it easier. How to obtain the attribute set? Reflection. Which of the following categories is it? Regardless of it, generic solutions.

To put it down so much, paste the core code

public static T1 UpdateObjectByDic<T1>(T1 scrobj, IDictionary<string, string> sourceobject, bool ignoreCase)     where T1 : new()    {      T1 result = scrobj;      PropertyInfo[] pifresults = typeof(T1).GetProperties();      foreach (var dic in sourceobject)      {        foreach (PropertyInfo pifresult in pifresults)        {          if (string.Compare(dic.Key, pifresult.Name, ignoreCase) == 0)          {           pifresult.SetValue(result, ChangeType(dic.Value, pifresult.PropertyType), null);            break;          }        }      }      return result;    }    public static Object ChangeType(object value, Type targetType)    {      Type convertType = targetType;      if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))      {        NullableConverter nullableConverter = new NullableConverter(targetType);        convertType = nullableConverter.UnderlyingType;      }      return Convert.ChangeType(value, convertType);    }

Here, T1 scrobj puts updates together. For example, when a form is added, a new object is passed in. If the form is updated, the original form data is passed in. The ChangeType method is mentioned below. The others are the attributes of the Data class that are nullable (int? DateTime? ) Traditional Convert. changeType has an exception, so you can simply change it. ignoreCase is the attribute (the value corresponding to the datafield at the front end) to check whether the processing is case-sensitive (usually case-insensitive, case Sensitive: it is believed that it will be drowned by front-end traffic ).

In this way, the core of the background data processing is complete, and some code for calling is also posted.

[WebMethod(EnableSession = true)]    public static string Save(Dictionary<string, string> jsondata)    {      string result = "0";      Model.Project pro = ConvertHandle.UpdateObjectByDic< Model.Project>(jsondata,new Model.Project,true);            pro.CreatorID = BLL.Sys_User.GetCurUser().ID.ToString();      pro.CreatorName = BLL.Sys_User.GetCurUser().Name;          prohandle.Insert(pro);      result = "1";       return result;    }

Here is the core use of the specific processing method call in the background, prohandle. insert (pro) saves the class to the database, pro. creatorID, pro. creatorName is some other information about the project. Here, the front-end data of a form is collected and processed in the backend. In addition to the data that is saved, it is all done.

At the end of the article, this is just a simple application. As I said, many front-end js frameworks have been done early, and the considerations are much more comprehensive than mine, background processing is based on my simple collection at the front end. Many third-party frameworks have a complete system. However, what I am talking about here is just a simple idea, if you do not have so many controls at the moment, can you simply implement this path. Of course, I strongly recommend that you do not duplicate the wheel, but be sure to understand the core role and principle of the wheel.

The above simple application based on Ajax form submission and background processing is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the customer's home.

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.