Based on Ajax form submission and background processing simple application _ajax related

Source: Internet
Author: User
Tags json

First of all say the form to submit it, to submit the form then you have to collect the form data (as for the verification of this I will not speak, to say leave next time), with jquery to get an HTML value or a simple $ ("Xxid"). Val () is over, but if a form collects a lot of data, There are a lot of sheets like this, and that's a sure way to die, and it's easy to be mistaken. So, we can simply define a collection rule, such as the data form controls to be uploaded back to the server, to mark them, and retrieve the tagged data together.

Take the simplest stylistic input as an example bar <input type= "text" id= "Txtcode" name= "Txtcode" datafield= "Code" style= "width:200px"/> We add a " DataField attribute, the value stored is the property name of the corresponding server-related class. With this mark the front desk to get the data is good.

We can set a common method like the following code

Getformdata:function (formid) {    
    var data = {};

    Gets the contents of
    the text file $ ("#" + 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 to get all the text inside the form, and put it into a data object, as for other forms control values how to take I do not say more, the principle is similar.

Then the next is to send the data to the server, I am here directly with jquery with Ajax.

var save = function (sender) {     
      $ (sender). Prop ("Disabled", true);//Disable the button to prevent the repeated sending of
      var data = Getformdata ("Form1"); C3/>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 ("Save success!") ");           
          }
          else if (msg.d = = "0") {
            alert ("Save failed!") ");
          }
        },
        complete:function (JQXHR, Textstatus) {
          $ (sender). Prop (" disabled ", false); Restore Button}}
      );
    

Here the "Xxxxx.aspx/save" is the AJAX processing page, the other is a WebMethod. Did a bit to prevent the customer hand speed too fast, the service processing is too slow, repeated click processing.

Such a form data collection, the return server is complete. Here, the advantage of using Json2.js's Json.stringify method to convert an object to a JSON character is to simply clean it without having to consider the JSON format problem for a JSON string.

Then the customer has collected the data well, the server should also be processed data. The key of the data we came from the foreground (JSON key), it is not possible to include all the properties of a data class. And there are a number of data classes, it should be which class only the server knows. So here we need to write a help conversion class. There is a problem here, it is possible that there are many data classes, I want to write a method for each class, it is not a pit? So we analyze the client to the service end of the data format, it is a set of key value pairs and will not repeat, then the equivalent of a dictionary<string, string>, there are many kinds of classes in the background, then at least we can determine an incoming parameter, outgoing is related to the class. Related classes? In the end is what kind of only to the specific background collection method to know. So, tidy up the idea, now have a dictionary<string, string> to become a data class, what is the data class what kind of attribute? Confusing, but this dictionary<string, string> key (key) can be seen as a subset of the set of data class attributes, and this dictionary<string, string> value (values) is a subset of this data class attribute value ToString (). That would be a good thing to do. How do I get a property set? Reflection. What are all these classes? Regardless of it, generics are resolved.

Say so much, put down 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 (s) Tring. Compare (DIC). Key, Pifresult. Name, ignoreCase) = = 0) {Pifresult. SetValue (Result, changetype (DIC). Value, Pifresult.
            PropertyType), NULL);
          Break
    }} return result;
      The 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); }

I am here T1 scrobj is the update to do together, such as adding a form to pass a new object to come in, if it is the update to the list of the original form is rumored to come in. Here incidentally the ChangeType method, the other is the data class some properties are nullable (int?) Datetime? And so on) the traditional convert.changetype will have an exception, so it is easy to change, ignorecase is the attribute (foreground that datafield corresponding value) to find whether to handle the case (generally regardless of the case, to the case of the casing is believed to be the foreground mouth water drowning).

So the background data processing core is over, the call part of the code 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 background of the specific processing method call the core use, Prohandle. Insert (PRO) stores the class in the database, Pro. Creatorid,pro. Creatorname for some other information on the project, these are not mentioned. Here a form of the foreground data collection, background processing, in addition to save that piece, are all finished, hehe.

In the end, here's just a simple application, like I said, this front desk collection, a lot of front JS framework has already done, consider more than I this more comprehensive, background processing I this is based on my simple collection of the front desk, many third-party frameworks have a complete system, but I said here is just a simple idea, When you do not have so many controls when you can make this path simple to achieve. Of course I strongly recommend not to reinvent the wheel, but be sure to understand the core role and principle of the wheel.

The above is based on Ajax form submission and background processing simple application is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.