ASP.NET_實踐透過POST方式來開啟另一webform_如何將C#或VB.NET的List透過Json.NET處裡完傳給js


此時可能已經填塞了兩個List物件
lsColDataKeyCollection
lsColDataValCollection
然後是透過Grid選取某列時做出傳送的

【發送端】父頁面
後端VB.NET Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim XC As New NameValueCollection
        ' ...... do something
        If Page.IsPostBack = False Then '頁面第一次載入只執行一次
            ' ...... do something
            
        End If

        AddHandler GridShipContent.SelectedIndexChanging, AddressOf OnGridViewSelectedIndexChanging
    End Sub
 
 
    Private Sub OnGridViewSelectedIndexChanging(sender As Object, e As GridViewSelectEventArgs)
        If e.NewSelectedIndex < 0 Then Exit Sub

  ' ...... do something
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "PostTest", "DoPostOpen()", True)
    End Sub


前端Js部分
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
        function DoPostOpen() {
            var keys = [];
            var vals = [];
            var rawJsondicKeyStr = '<%=Newtonsoft.Json.JsonConvert.SerializeObject(lsColDataKeyCollection)%>';
            //document.write("RawJsonKey:" + rawJsondicKeyStr + ";" + "<br>");
            var rawJsondicValStr = '<%=Newtonsoft.Json.JsonConvert.SerializeObject(lsColDataValCollection)%>';
            //document.write("RawJsonVal:" + rawJsondicValStr + ";" + "<br>");

            //用json2.js的JSON做parser避免因應IE8,7,6 沒有javascript原生的Json解析API問題
            var listKey = JSON.parse(rawJsondicKeyStr)
            //document.write("listKey:" + listKey + ";" + "<br>");
            var listVal = JSON.parse(rawJsondicValStr)
            //document.write("listVal:" + listVal + ";" + "<br>");



            for (var idxKey = 0; idxKey < listKey.length; idxKey++) {
                keys[idxKey] = listKey[idxKey];
                vals[idxKey] = listVal[idxKey];
                //document.write(listKey[idxKey])
                //document.write("<br>")
            }
            openWindowByPost("EditForm.aspx", "web", keys, vals, 50,50,400,520);
        }

        function openWindowByPost(url, name, keys, values, ArgTop, ArgLeft, ArgWidth, ArgHeight) {
            //alert("openWindowByPost begin");
            var newWindow = window.open(url, name, "top=" + ArgTop + ",left=" + ArgLeft + ",width=" + ArgWidth + ",height=" + ArgHeight + ", toolbar=no, menubar=no, scrollbars=no,location=no,directories=no , status=no");

            if (!newWindow)
                return false;
            //alert("openWindowByPost pass window object check");
            var html = "";
            html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
            if (keys && values && (keys.length == values.length))
                for (var i = 0; i < keys.length; i++)
                    html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";
            html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()";
            html += "<" + "/script>";
            html += "<" + "/body>";
            html += "<" + "/html>";
            newWindow.document.write(html);
            return newWindow;
        }


這裡透過Json.NET 將List物件序列化給 js
前端 js 再引入Json2.js 確保不會因為IE太早期版本而不支援原生js 的JSON API

可透過Nuget來配置安裝
這樣就不需要一個一個指派,可直接Iterate Assign。






【接收端】子頁面(sub.aspx)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 Dim lsColName As New List(Of String)
 Dim lsColVal As New List(Of String)
 If Request.Form.AllKeys.ToList().Count > 0 Then
  '全英文數字內容傳輸時候
            For Each postVal In Request.Form.Keys
         lsColName.Add(postVal)
  lsColVal.Add(Request.Form(postVal))
            Next
  '特定某些傳輸欄位包含中文時候,以下示例是Key已經確保是英文(因為是開發者自訂的)
  'lsColName.Add(postVal)
  'If postVal = "unit" Then
  ' Dim strChineseContent As String = "\u" & Request.Form(postVal) '\u4e2a
        '    Dim strUniToOriStrContent As String = UnicodeToStr(strChineseContent) '\u4e2a -> 个
  ' lsColVal.Add(strUniToOriStrContent)
  'Else
  ' lsColVal.Add(Request.Form(postVal))
  'End If
 End If
 
 '.... do something
 
 '如果在此aspx網頁上你想透過按鈕讓父頁面更新傳回內容則可將如下註解掉的取消
 'Step1.父頁面請安置一個按鈕調成style為display:none,並將父頁面更新邏輯寫入是件區塊中。
 'Step2.透過session存內容 後續在父頁面事件可在調用session對應Key獲取子頁面指派的值
 'AddHandler btnSendBack.Click, AddressOf OnBtnSendBack
  
End Sub


Private Sub OnBtnSendBack(sender As Object, e As EventArgs)
 Dim strJs As String = "window.opener.document.getElementById('btnSubTrigger').click();"
 'Dim strJs As String = "window.opener.SetVal(" & Request.Form("txt_ok_qty") & ");" '---> ok_qty: 14
 Session("P_Key1") = Request.Form("Key1")
    Session("P_Key2") = Request.Form("Key2")
 ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ParentButtonClick", strJs, True)

 strJs = "window.close();"
    Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "CloseWin", strJs, True)
End Sub


Reference:

[JavaScript]window.open的post與get傳遞參數比較
https://dotblogs.com.tw/puma/archive/2008/09/03/5288.aspx
How do I pass a list from aspx to javascript?
https://stackoverflow.com/questions/3415550/how-do-i-pass-a-list-from-aspx-to-javascript
[JavaScript] JSON stringify and parse
https://oawan.me/2016/javascript-json-stringify-and-parse/
如何在Visual Studio項目中安裝Json.Net
https://www.newtonsoft.com/json
https://riptutorial.com/zh-TW/json-net/example/6086/%E5%A6%82%E4%BD%95%E5%9C%A8visual-studio%E9%A0%85%E7%9B%AE%E4%B8%AD%E5%AE%89%E8%A3%9Djson-net
[Day 22] C#中Json的序列化和反序列化的幾種方式(三)
https://ithelp.ithome.com.tw/articles/10195057
jQuery JSON
https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/289501/
https://blog.xuite.net/dizzy03/murmur/44844092-%5BjQuery%5D%5Bjavascript%5D+%E5%88%A9%E7%94%A8jquery+plug-in%E5%B0%87array%E8%BD%89%E6%88%90json
https://github.com/krinkle/jquery-json
Converting a JSON Text to a JavaScript Object
https://www.w3schools.com/js/js_json.asp
https://kingweblife.blogspot.com/2016/03/jsonparse.html
解决IE浏览器兼容性问题:“JSON”未定义
https://blog.csdn.net/liu865033503/article/details/78191521





留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header