Author: Yan Shiwei Email: ikmb@163.com reprinted author
Note: 1. js combines the name and value of the form element into json format based on the class attribute of the form element. JSON data can be combined in a targeted manner using the class attribute of the form element.
2. the backend ASP. NET uses JavaScriptSerializer to deserialize the object into a real column.
3. Benefits: It simplifies front-end Data Reading and backend Data assignment.
Copy codeThe Code is as follows:
Function GetJSONStr (class_name ){
Var a = [];
// Text box
$ ("." + Class_name). filter (": text"). each (function (I ){
// Alert (this. name );
// Alert (this. value );
A. push ({name: this. name, value: this. value });
});
// Drop-down list
$ ("." + Class_name). filter ("select"). each (function (I ){
// Alert (this. name );
// Alert (this. value );
A. push ({name: this. name, value: this. value });
});
// Single region
$ ("." + Class_name). filter (": radio"). filter (": checked"). each (function (I ){
// Alert (this. name );
// Alert (this. value );
A. push ({name: this. name, value: this. value });
});
// Check box starts
Var temp_cb = "";
$ ("." + Class_name). filter (": checkbox"). filter (": checked"). each (function (I ){
If (temp_cb.indexOf (this. name) =-1 ){
Temp_cb + = this. name + ",";
}
});
Var temp_cb_arr = temp_cb.split (",");
Var cb_name = "";
Var cb_value = "";
For (var temp_cb_ I = 0; temp_cb_ I <temp_cb_arr.length-1; temp_cb_ I ++ ){
Cb_name = temp_cb_arr [temp_cb_ I];
Var cb_value_length = $ ("input [name = '" + temp_cb_arr [temp_cb_ I] + "']: checked"). length;
$ ("Input [name = '" + temp_cb_arr [temp_cb_ I] + "']: checked"). each (function (I ){
If (I = cb_value_length-1)
Cb_value + = this. value;
Else
Cb_value + = this. value + ",";
});
// Alert (cb_name );
// Alert (cb_value );
A. push ({name: cb_name, value: cb_value });
}
// Check box ends
// JSON
Var temp_json = "";
For (var json_ I = 0; json_ I <a. length; json_ I ++ ){
If (json_ I! = A. length-1 ){
Temp_json + = '"' + a [json_ I]. name + '": "' + a [json_ I]. value + '",';
}
Else {
Temp_json + = '"' + a [json_ I]. name + '": "' + a [json_ I]. value + '"';
}
}
Return "{" + temp_json + "}";
}
ASP. NET
Copy codeThe Code is as follows:
Public partial class test: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer ();
String r = Request. Form ["msg"];
// {"Name": "MyName1", "Single": "one "}
T_json t_json_object = Serializer. Deserialize <t_json> (r );
Response. Write (t_json_object.Name );
Response. End ();
}
}
Class t_json
{
Public DateTime Name;
Public string Single;
}