基於jquery ajax html 模板 的母子表的子表table增刪操作.記一下,免得重複勞動.既簡潔又容易擴充.

來源:互聯網
上載者:User
 <!-- 擴充屬性-->    <div  tabpanel="propetytabpanel" class="form_table_input">                  <table id="tablist" class="datatable" border="1" cellspacing="0" bordercolorlight="#dddddd"           bordercolordark="#ffffff" cellpadding="0" width="100%">           <tbody>               <tr>                    <th width="20%">                       屬性名稱                   </th>                   <th width="20%">                       英文屬性名稱                   </th>                    <th width="20%">                       排序                   </th>                    <th width="10%">                       操作                   </th>               </tr>            </tbody>           <tbody id="ExtendPropetyContent">           </tbody>           <tbody id="ExtendPropetyContentCcontentTemple" style="display:none;">                <tr DataId="{ID}">                   <td>                       {PropertyName}                   </td>                   <td>                       {PropertyEnglishName}                   </td>                    <td>                       <input type="text" class="Sort" value="{Sort}" />                   </td>                    <td>                        <a  href="javascript:DelExtendPropety({ID})"  >刪除</a>                   </td>               </tr>           </tbody>                  </table>        <script>                      var template = JQ("#ExtendPropetyContentCcontentTemple").html();           var $content = JQ("#ExtendPropetyContent");            var ProductTypeID = JQ("#ProductTypeID").val();            var Sort = 0;            function DelExtendPropety(id) {                if (confirm('確定要永久刪除該資訊嗎?刪除後將不能被恢複!')) {                    var param = "Option=delpropety&ProductTypeID=" + ProductTypeID + "&id=" + id;                    var options = {                        method: 'post',                        parameters: param,                        onComplete: function (transport) {                            var retv = transport.responseText;                            if (retv.indexOf("成功") > 0) {                                $content.find("*[DataId=" + id + "]").remove();                            } else {                                alert(retv);                            }                        }                    }                } else {                    return false;                }                new Ajax.Request('product_type_edit_ajax.ashx', options);            }            function AddExtendPropety(rowdata) {                var t = template;               //自動排序               rowdata.Sort = Sort++;               for (var p in rowdata) {                   var reg = new RegExp("{" + p + "}","ig"); //只有Regex才替換全部                   t = t.replace(reg, rowdata[p]);               }               //第一個元素上綁定資料               var c = JQ(t);               var rowhtml = c.first().data(rowdata)//                           .click(function () {//                               alert(JQ(this).data().ID);//                           });               $content.append(c);           }            //載入擴充屬性           function loadExtendPropety() {                             JQ.ajax({                   type: "POST",                   dataType: "json",                   url: "product_type_edit_ajax.ashx",                   data: { "ProductTypeID": ProductTypeID, "Option": "GetExtendPropety" },                   success: function (data) {                        for (var i = 0; i < data.length; i++) {                           AddExtendPropety(data[i]);                       }                    }               });           }           //載入資料           loadExtendPropety();           function showFuHaoWindow() {               var returnvalue = window.showModalDialog('product_existFuHao.aspx?propertyId=' + ProductTypeID, null, 'dialogheight=600; dialogwidth=800;  edge=Raised; center=Yes;  resizable=Yes; status=Yes;');                              for (var i = 0; i < returnvalue.length; i++) {                   AddExtendPropety({ "PropertyName": returnvalue[i],"ID":0 ,"PropertyEnglishName":""});               }           }           //把系列擴充屬性拼裝成起來傳到後台           function joinExtendProperty() {               var datas = [];               $content.children().each(function () {                   var d = JQ(this).data();                   d.PropertyValue = "";                   d.TypeID = ProductTypeID;                   //這些是業務操作可根據需要修改                   d.Sort = JQ(this).find("input.Sort").val(); //更新可輸入項                   datas.push(d);               });               var json = JQ.toJSON(datas);               json = eval(json);  //這句話是toJSON返回的字串把 " 換成 \" 了所以要轉換一次               JQ("#extendpropty").val(json);            }       </script>       <br />        <a   class="inputbutton_a" target="_blank" onclick="javascript:showFuHaoWindow()">添加符號屬性</a>         <br />        <input type="hidden" value="" id="extendpropty" name="extendpropty" />   </div>

 

product_type_edit_ajax.ashx

後台代碼

 

<%@ WebHandler Language="C#" Class="product_type_edit_ajax" %>using System;using System.Web;using System.Web.SessionState;public class product_type_edit_ajax : IHttpHandler, IRequiresSessionState{        public void ProcessRequest (HttpContext context) {        context.Response.ContentType = "text/plain";                if (Request["Option"] != string.Empty )        {            string Option = context.Request.Form["Option"].Trim();             int propertyId = PageRequest.GetFormInt("ProductTypeID");            if (Option == "delpropety")            {                int id = PageRequest.GetFormInt("id");                context.Response.Write( delpropety(id, propertyId));            }            else if (Option == "GetExtendPropety")            {                context.Response.Write(GetPropertyList(propertyId));            }            context.Response.End();            return;        }                              }    /// <summary>    /// 擷取產品系列屬性 的Html     /// </summary>    /// <returns></returns>    protected string GetPropertyList(int productTypeId)    {         //Shop.BLL.Product.ProductType bll = new Shop.BLL.Product.ProductType();        var  dataPage = new List<User>();//bll.GetProductPropertyAllByWhere(productTypeId,"1=1");        //JavaScriptSerializer類在System.Web.Extensions.dll中,注意添加這個引用          System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();        //JSON序列化          string result = serializer.Serialize(dataPage);        return result;        //Console.WriteLine("使用JavaScriptSerializer序列化後的結果:{0},長度:{1}", result, result.Length);        //JSON還原序列化          //user = serializer.Deserialize<User>(result);        //Console.WriteLine("使用JavaScriptSerializer還原序列化後的結果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority);             }        /// <summary>    /// 刪除產品類型的屬性 擴充屬性(參數啥的)    /// </summary>    /// <param name="id"></param>    /// <param name="propertyId"></param>    private string delpropety(int id, int propertyId)    {/*刪除操作*/      return "刪除成功";    }            public bool IsReusable {        get {            return false;        }    }}

 還有一段後台儲存的代碼

 /// <summary>        /// 儲存擴充屬性        /// </summary>        /// <param name="productTypeId">產品系列ID</param>        private void SaveExtendPropty(int productTypeId)        {            string json =Request["extendpropty"];            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();                         //JSON還原序列化  產品系列對應的擴充屬性            var extendProperty = serializer.Deserialize<List<Model.Product.ProductTypeProperty>>(json);            if (extendProperty == null) return;            Shop.BLL.Product.ProductType bll = new Shop.BLL.Product.ProductType();            foreach (Model.Product.ProductTypeProperty extend in extendProperty)            {                if (extend.ID > 0)                {                    bll.UpdateProductProperty(extend,extend.TypeID);                }                else                {                    bll.AddProductProperty(extend);                }            }                        //Console.WriteLine("使用JavaScriptSerializer還原序列化後的結果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority);                     }

 

 

我這裡的Jquery簡寫成JQ 如果你需要的話可以改成$

另外這裡的JQ.toJSON()這個函數是來自與一個開源庫 jquery.json-2.2.js

這個代碼主要是實現,主表附帶子表這種情況,

需要儲存前就編輯的情況... 主表儲存的時候,子表一併儲存..主表不儲存,子表也不儲存..

一對多關聯性的資料編輯介面適合使用這個代碼..

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.