在本指南中,您將設定網頁和自訂 Web 範本,該範本將使用伺服器邏輯從連絡人表格讀取、寫入、更新和刪除記錄。
步驟 1:建立伺服器邏輯
登入 Power Pages。
選擇站點 + 編輯。
流覽至 [ 設定 ] 工作區,然後選取 [ 伺服器邏輯 (預覽版)]。
選取 [+新增伺服器邏輯]。
輸入伺服器邏輯的名稱。 此名稱會在 API 中用作建構伺服器邏輯 API 時的資源識別碼。
範例:dataverse-crud-operations
選取 [+新增角色] 以指派適當的 Web 角色。
選取名稱旁的 3 個點 (...),然後選取 編輯程式碼。
選取 [ 開啟 Visual Studio Code ] 以撰寫自訂邏輯。 您會在檔案中找到預先定義的方法和腳本。
定義伺服器邏輯方法來讀取、編輯、建立、刪除聯絡人記錄。
閱讀:在 get 方法中新增以下腳本
const entitySetName = Server.Context.QueryParameters["entitySetName"]; if (!Server.Context.QueryParameters["id"]) { return Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName); } else { const id = Server.Context.QueryParameters["id"]; // Context reference return Server.Connector.Dataverse.RetrieveRecord(entitySetName, id); }創建:在 post 方法中添加以下腳本
const data = Server.Context.Body; const entitySetName = Server.Context.QueryParameters["entitySetName"]; return Server.Connector.Dataverse.CreateRecord(entitySetName, data);更新:在 put 方法中添加以下腳本
const id = Server.Context.QueryParameters["id"]; const data = Server.Context.Body; return Server.Connector.Dataverse.UpdateRecord("accounts", id, data);刪除:在 del 方法內新增
const id = Server.Context.QueryParameters["id"]; const entitySetName = Server.Context.QueryParameters["entitySetName"]; Server.Logger.Log("Entity Set name:" + entitySetName); return Server.Connector.Dataverse.DeleteRecord(entitySetName, id);儲存檔案。
以下是可以貼上的完整伺服器邏輯程式碼
function get() { try { Server.Logger.Log("GET called"); // Logger reference const entitySetName = Server.Context.QueryParameters["entitySetName"]; const additionParameters = Server.Context.QueryParameters['additionalParameters']; if (!Server.Context.QueryParameters["id"]) { const response = Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName,additionParameters); return response; } else{ const id = Server.Context.QueryParameters["id"]; // Context reference const response = Server.Connector.Dataverse.RetrieveRecord(entitySetName, id,additionParameters); return response; } } catch (err) { Server.Logger.Error("GET failed: " + err.message); return JSON.stringify({ status: "error", method: "GET", message: err.message }); } } function post() { try { Server.Logger.Log("POST called"); const data = Server.Context.Body; const entitySetName = Server.Context.QueryParameters["entitySetName"]; return Server.Connector.Dataverse.CreateRecord(entitySetName, data); } catch (err) { Server.Logger.Error("POST failed: " + err.message); return JSON.stringify({ status: "error", method: "POST", message: err.message }); } } function put() { try { Server.Logger.Log("PUT called"); const id = Server.Context.QueryParameters["id"]; const data = Server.Context.Body; const entitySetName = Server.Context.QueryParameters["entitySetName"]; return Server.Connector.Dataverse.UpdateRecord(entitySetName, id, data); } catch (err) { Server.Logger.Error("PUT failed: " + err.message); return JSON.stringify({ status: "error", method: "PUT", message: err.message }); } } function del() { try { // "delete" keyword should not be used in script file. Server.Logger.Log("DEL called"); const id = Server.Context.QueryParameters["id"]; const entitySetName = Server.Context.QueryParameters["entitySetName"]; return Server.Connector.Dataverse.DeleteRecord(entitySetName, id); } catch (err) { Server.Logger.Error("Deletion failed: " + err.message); return JSON.stringify({ status: "error", method: "DEL", message: err.message }); } }
第 2 步:創建網頁
在 [頁面] 工作區中,選取 [+ 頁面]。
在 [新增頁面] 對話方塊中,在 [名稱] 方塊中輸入 [伺服器邏輯],然後選取 [從空白版面配置開始]。
選取 ,然後新增。
選擇右上角的編輯 代碼 選項。
選取 開啟 Visual Studio Code。
複製下列範例程式碼片段,並將其貼到頁面區段的標籤之間
<div></div>。<style> #processingMsg { padding: 6px 12px; background: #eee; border-radius: 4px; position: fixed; top: 10px; left: 50%; transform: translateX(-50%); display: none; z-index: 9999; text-align: center; font-weight: bold; } table { border-collapse: collapse; width: 100%; margin-top: 10px; font-family: Arial, sans-serif; } th, td { border: 1px solid #ccc; padding: 6px; text-align: left; } button { cursor: pointer; border: 1px solid #aaa; padding: 4px 8px; border-radius: 4px; background: #fff; font-size: 14px; margin-right: 2px; } button.add { color: green; } button.save { color: green; } button.cancel { color: orange; } button.delete { color: red; } input { width: 95%; box-sizing: border-box; } td.actions { white-space: nowrap; } </style> <div id="processingMsg">Processing...</div> <div id="dataTable"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(function() { // --- safeAjax wrapper --- (function(webapi, $) { function safeAjax(ajaxOptions) { var dfd = $.Deferred(); shell.getTokenDeferred().done(function(token) { ajaxOptions.headers = ajaxOptions.headers || {}; ajaxOptions.headers["__RequestVerificationToken"] = token; $.ajax(ajaxOptions) .done((data, ts, jq) => validateLoginSession(data, ts, jq, dfd.resolve)) .fail(dfd.reject); }).fail(() => dfd.rejectWith(this, arguments)); return dfd.promise(); } webapi.safeAjax = safeAjax; })(window.webapi = window.webapi || {}, jQuery); // --- notification banner --- const notify = (function() { const $m = $('#processingMsg'); let s = 0, t; return { show: (msg = 'Processing...') => { $m.text(msg); if (!s) clearTimeout(t), $m.show(); s++; }, hide: () => { s = Math.max(0, s - 1); if (!s) clearTimeout(t), t = setTimeout(() => $m.hide(), 300); } }; })(); function ajaxCall(msg, opts) { notify.show(msg); return webapi.safeAjax(opts) .fail(r => alert(r.responseJSON?.error?.message || 'Server logic not available')) .always(notify.hide); } // --- Table config --- const cols = [ { name: 'firstname', label: 'First Name' }, { name: 'lastname', label: 'Last Name' }, { name: 'emailaddress1', label: 'Email' }, { name: 'telephone1', label: 'Telephone' } ]; let data = []; function render() { const html = `<table> <thead> <tr> ${cols.map(c => `<th>${c.label}</th>`).join('')} <th>Actions <button class="add">➕</button></th> </tr> </thead> <tbody> ${data.map(r => `<tr data-id="${r.id}" data-name="${r.fullname}"> ${cols.map(c => `<td data-attribute="${c.name}" data-value="${r[c.name] || ''}">${r[c.name] || ''}</td>`).join('')} <td class="actions"> <button class="delete">🗑️</button> </td> </tr>`).join('')} </tbody> </table>`; $('#dataTable').html(html); } function addRecord(r) { data.unshift(r); render(); } function removeRecord(id) { data = data.filter(r => r.id !== id); render(); } function updateRecord(id, attr, val) { const r = data.find(r => r.id === id); if (r) { r[attr] = val; render(); } } // --- Events --- $('#dataTable').on('dblclick', 'tr', function() { const $tr = $(this); if ($tr.hasClass('editing')) return; // prevent double edit $tr.addClass('editing'); $tr.data('original', $tr.find('td[data-attribute]').map(function() { return $(this).text(); }).get()); $tr.find('td[data-attribute]').each(function() { const $td = $(this); const oldVal = $td.text(); $td.html(`<input type="text" value="${oldVal}" data-attr="${$td.data('attribute')}" />`); }); const $actions = $tr.find('td.actions'); $actions.append('<button class="save">✅</button><button class="cancel">❌</button>'); }); $('#dataTable').on('click', '.save', function() { const $tr = $(this).closest('tr'); const id = $tr.data('id'); const updates = {}; $tr.find('input').each(function() { updates[$(this).data('attr')] = $(this).val(); }); ajaxCall('Updating...', { type: 'PUT', url: `/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&id=${id}`, contentType: 'application/json', data: JSON.stringify(updates), success: () => { Object.assign(data.find(r => r.id === id), updates); render(); } }); }); $('#dataTable').on('click', '.cancel', function() { const $tr = $(this).closest('tr'); const original = $tr.data('original'); $tr.find('td[data-attribute]').each(function(i) { $(this).text(original[i]); }); $tr.removeClass('editing'); $tr.find('button.save, button.cancel').remove(); }); $('#dataTable').on('click', '.delete', function() { const $tr = $(this).closest('tr'); if (confirm('Delete "' + $tr.data('name') + '"?')) { ajaxCall('Deleting...', { type: 'DELETE', url: `/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&id=${$tr.data('id')}`, contentType: 'application/json', success: () => removeRecord($tr.data('id')) }); } }); $('#dataTable').on('click', '.add', function() { const r = { firstname: 'Alton', lastname: 'Stott' + Math.floor(Math.random() * 900 + 100), emailaddress1: 'Alton.Stott@contoso.com', telephone1: '555-123-4567' }; ajaxCall('Adding...', { type: 'POST', url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts', contentType: 'application/json', data: JSON.stringify(r), success: (res, s, xhr) => { r.id = xhr.getResponseHeader('entityid'); r.fullname = r.firstname + ' ' + r.lastname; addRecord(r); } }); }); ajaxCall('Loading...', { type: 'GET', url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&additionalParameters=$select=fullname,firstname,lastname,emailaddress1,telephone1', contentType: 'application/json' }).done(res => { try { const p = JSON.parse(res.data); const b = JSON.parse(p.Body); data = (b.value || []).map(r => ({ ...r, id: r.contactid, fullname: r.fullname })); render(); } catch (e) { console.error(e); } }); }); </script>
步驟 3:設定許可權
建立 Web 角色
如果您目前沒有擁有透過伺服器邏輯存取該資料表的許可權的網頁角色,或者需要在不同的上下文中存取資料,下列步驟會示範如何建立新的網頁角色並指派資料表許可權。
- 啟動 入口網站管理應用程式。
- 在左窗格的 [ 安全性 ] 區段中,選取 [Web 角色]。
- 選擇 新建。
- 在 [ 名稱 ] 方塊中,輸入 [伺服器邏輯 使用者] (或最能反映存取此功能之使用者角色的任何名稱)。
- 在 網站清單 中,選取您的網站記錄。
- 選取 [儲存]。
建立資料表權限
- 啟動 Power Pages 設計工作室。
- 選取 [安全性 ] 工作區。
- 在 [保護] 區段下,選取 [資料表許可權]。
- 選取 [新增許可權]。
- 在 [名稱 ] 方塊中,輸入 [連絡人資料表權限]。
- 在 [資料表名稱] 清單中,選取 [連絡人 (連絡人)]。
- 在 [存取類型] 清單中,選取 [全域]。
- 選取 讀取、 寫入、 建立和 刪除 權限。
- 選取 [+ 新增角色], 然後選取您稍早選取或建立的 Web 角色 。
- 選取儲存後關閉。
將連絡人新增至 Web 角色
- 啟動 入口網站管理應用程式。
- 在左窗格的 [安全性] 區段中,選取 [連絡人]。
- 選取您要在此範例中用於伺服器邏輯的連絡人。
備註
此連絡人是此範例中用於測試伺服器邏輯的使用者帳戶。 請務必在入口網站中選取正確的連絡人。
- 選取 相關>Web 角色。
- 選取 [新增現有的 Web 角色]。
- 選取稍早建立的 伺服器邏輯使用者 角色。
- 選取 ,然後新增。
- 選取儲存後關閉。
步驟 4:使用伺服器邏輯讀取、檢視、編輯、建立和刪除
若要測試 Web API 功能:
- 選取 [預覽],然後選擇 [桌面]。
- 使用已獲指派您稍早建立的 伺服器邏輯使用者 角色的使用者帳戶登入您的網站。
- 移至先前建立的 伺服器邏輯 網頁。