Acara
19 Nov, 23 - 21 Nov, 23
Bergabunglah dengan sesi online di Microsoft Ignite yang dibuat untuk memperluas keterampilan Anda dan membantu Anda mengatasi masalah kompleks saat ini.
Daftar sekarangBrowser ini sudah tidak didukung.
Mutakhirkan ke Microsoft Edge untuk memanfaatkan fitur, pembaruan keamanan, dan dukungan teknis terkini.
Oleh Rick Anderson
Tutorial ini menunjukkan cara memanggil API web ASP.NET Core dengan JavaScript, menggunakan Fetch API.
Di bagian ini, Anda akan menambahkan halaman HTML yang berisi formulir untuk membuat dan mengelola item yang harus dilakukan. Penanganan aktivitas dilampirkan ke elemen di halaman. Penanganan aktivitas menghasilkan permintaan HTTP ke metode tindakan API web. Fungsi Fetch API fetch
memulai setiap permintaan HTTP.
Fungsi fetch
mengembalikan objek, yang berisi respons HTTP yang direpresentasikan Promise
sebagai Response
objek. Pola umumnya adalah mengekstrak isi respons JSON dengan memanggil json
fungsi pada Response
objek. JavaScript memperbarui halaman dengan detail dari respons API web.
Panggilan paling fetch
sederhana menerima satu parameter yang mewakili rute. Parameter kedua, yang init
dikenal sebagai objek, bersifat opsional. init
digunakan untuk mengonfigurasi permintaan HTTP.
Program.cs
:using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
var app = builder.Build();
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Buat folder wwwroot di akar proyek.
Buat folder css di dalam folder wwwroot .
Buat js folder di dalam folder wwwroot .
Tambahkan file HTML bernama index.html
ke folder wwwroot . Ganti konten index.html
dengan markup berikut:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>To-do CRUD</title>
<link rel="stylesheet" href="css/site.css" />
</head>
<body>
<h1>To-do CRUD</h1>
<h3>Add</h3>
<form action="javascript:void(0);" method="POST" onsubmit="addItem()">
<input type="text" id="add-name" placeholder="New to-do">
<input type="submit" value="Add">
</form>
<div id="editForm">
<h3>Edit</h3>
<form action="javascript:void(0);" onsubmit="updateItem()">
<input type="hidden" id="edit-id">
<input type="checkbox" id="edit-isComplete">
<input type="text" id="edit-name">
<input type="submit" value="Save">
<a onclick="closeInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Is Complete?</th>
<th>Name</th>
<th></th>
<th></th>
</tr>
<tbody id="todos"></tbody>
</table>
<script src="js/site.js" asp-append-version="true"></script>
<script type="text/javascript">
getItems();
</script>
</body>
</html>
Tambahkan file CSS bernama site.css
ke folder wwwroot/css . Ganti konten site.css
dengan gaya berikut:
input[type='submit'], button, [aria-label] {
cursor: pointer;
}
#editForm {
display: none;
}
table {
font-family: Arial, sans-serif;
border: 1px solid;
border-collapse: collapse;
}
th {
background-color: #f8f8f8;
padding: 5px;
}
td {
border: 1px solid;
padding: 5px;
}
Tambahkan file JavaScript bernama site.js
ke folder wwwroot/js. Ganti isi site.js
dengan kode berikut:
const uri = 'api/todoitems';
let todos = [];
function getItems() {
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
}
function addItem() {
const addNameTextbox = document.getElementById('add-name');
const item = {
isComplete: false,
name: addNameTextbox.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getItems();
addNameTextbox.value = '';
})
.catch(error => console.error('Unable to add item.', error));
}
function deleteItem(id) {
fetch(`${uri}/${id}`, {
method: 'DELETE'
})
.then(() => getItems())
.catch(error => console.error('Unable to delete item.', error));
}
function displayEditForm(id) {
const item = todos.find(item => item.id === id);
document.getElementById('edit-name').value = item.name;
document.getElementById('edit-id').value = item.id;
document.getElementById('edit-isComplete').checked = item.isComplete;
document.getElementById('editForm').style.display = 'block';
}
function updateItem() {
const itemId = document.getElementById('edit-id').value;
const item = {
id: parseInt(itemId, 10),
isComplete: document.getElementById('edit-isComplete').checked,
name: document.getElementById('edit-name').value.trim()
};
fetch(`${uri}/${itemId}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(() => getItems())
.catch(error => console.error('Unable to update item.', error));
closeInput();
return false;
}
function closeInput() {
document.getElementById('editForm').style.display = 'none';
}
function _displayCount(itemCount) {
const name = (itemCount === 1) ? 'to-do' : 'to-dos';
document.getElementById('counter').innerText = `${itemCount} ${name}`;
}
function _displayItems(data) {
const tBody = document.getElementById('todos');
tBody.innerHTML = '';
_displayCount(data.length);
const button = document.createElement('button');
data.forEach(item => {
let isCompleteCheckbox = document.createElement('input');
isCompleteCheckbox.type = 'checkbox';
isCompleteCheckbox.disabled = true;
isCompleteCheckbox.checked = item.isComplete;
let editButton = button.cloneNode(false);
editButton.innerText = 'Edit';
editButton.setAttribute('onclick', `displayEditForm(${item.id})`);
let deleteButton = button.cloneNode(false);
deleteButton.innerText = 'Delete';
deleteButton.setAttribute('onclick', `deleteItem(${item.id})`);
let tr = tBody.insertRow();
let td1 = tr.insertCell(0);
td1.appendChild(isCompleteCheckbox);
let td2 = tr.insertCell(1);
let textNode = document.createTextNode(item.name);
td2.appendChild(textNode);
let td3 = tr.insertCell(2);
td3.appendChild(editButton);
let td4 = tr.insertCell(3);
td4.appendChild(deleteButton);
});
todos = data;
}
Perubahan pada pengaturan peluncuran proyek ASP.NET Core mungkin diperlukan untuk menguji halaman HTML secara lokal:
launchUrl
Hapus properti untuk memaksa aplikasi dibuka di index.html
—file default proyek.Sampel ini memanggil semua metode CRUD API web. Berikut ini adalah penjelasan tentang permintaan API web.
Dalam kode berikut, permintaan HTTP GET dikirim ke rute api/todoitems :
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
Ketika API web mengembalikan kode status yang berhasil, _displayItems
fungsi dipanggil. Setiap item yang harus dilakukan dalam parameter array yang diterima oleh _displayItems
ditambahkan ke tabel dengan tombol Edit dan Hapus . Jika permintaan API web gagal, kesalahan dicatat ke konsol browser.
Dalam kode berikut:
item
dinyatakan untuk membangun representasi harfiah objek dari item yang harus dilakukan.method
—menentukan kata kerja tindakan HTTP POST.body
—menentukan representasi JSON dari isi permintaan. JSON diproduksi dengan meneruskan literal objek yang disimpan ke item
fungsi JSON.stringify .headers
—menentukan Accept
header permintaan HTTP dan Content-Type
. Kedua header diatur ke application/json
untuk menentukan jenis media yang diterima dan dikirim, masing-masing.function addItem() {
const addNameTextbox = document.getElementById('add-name');
const item = {
isComplete: false,
name: addNameTextbox.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getItems();
addNameTextbox.value = '';
})
.catch(error => console.error('Unable to add item.', error));
}
Ketika API web mengembalikan kode status yang berhasil, getItems
fungsi dipanggil untuk memperbarui tabel HTML. Jika permintaan API web gagal, kesalahan dicatat ke konsol browser.
Memperbarui item yang harus dilakukan mirip dengan menambahkan item; namun, ada dua perbedaan signifikan:
method
oleh opsi .fetch(`${uri}/${itemId}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(() => getItems())
.catch(error => console.error('Unable to update item.', error));
Untuk menghapus item yang harus dilakukan, atur opsi permintaan method
ke DELETE
dan tentukan pengidentifikasi unik item di URL.
fetch(`${uri}/${id}`, {
method: 'DELETE'
})
.then(() => getItems())
.catch(error => console.error('Unable to delete item.', error));
Lanjutkan ke tutorial berikutnya untuk mempelajari cara membuat halaman bantuan API web:
Tutorial ini menunjukkan cara memanggil API web ASP.NET Core dengan JavaScript, menggunakan Fetch API.
Di bagian ini, Anda akan menambahkan halaman HTML yang berisi formulir untuk membuat dan mengelola item yang harus dilakukan. Penanganan aktivitas dilampirkan ke elemen di halaman. Penanganan aktivitas menghasilkan permintaan HTTP ke metode tindakan API web. Fungsi Fetch API fetch
memulai setiap permintaan HTTP.
Fungsi fetch
mengembalikan objek, yang berisi respons HTTP yang direpresentasikan Promise
sebagai Response
objek. Pola umumnya adalah mengekstrak isi respons JSON dengan memanggil json
fungsi pada Response
objek. JavaScript memperbarui halaman dengan detail dari respons API web.
Panggilan paling fetch
sederhana menerima satu parameter yang mewakili rute. Parameter kedua, yang init
dikenal sebagai objek, bersifat opsional. init
digunakan untuk mengonfigurasi permintaan HTTP.
Konfigurasikan aplikasi untuk menyajikan file statis dan mengaktifkan pemetaan file default. Kode yang disorot berikut diperlukan dalam Configure
metode Startup.cs
:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Buat folder wwwroot di akar proyek.
Buat folder css di dalam folder wwwroot .
Buat js folder di dalam folder wwwroot .
Tambahkan file HTML bernama index.html
ke folder wwwroot . Ganti konten index.html
dengan markup berikut:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>To-do CRUD</title>
<link rel="stylesheet" href="css/site.css" />
</head>
<body>
<h1>To-do CRUD</h1>
<h3>Add</h3>
<form action="javascript:void(0);" method="POST" onsubmit="addItem()">
<input type="text" id="add-name" placeholder="New to-do">
<input type="submit" value="Add">
</form>
<div id="editForm">
<h3>Edit</h3>
<form action="javascript:void(0);" onsubmit="updateItem()">
<input type="hidden" id="edit-id">
<input type="checkbox" id="edit-isComplete">
<input type="text" id="edit-name">
<input type="submit" value="Save">
<a onclick="closeInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Is Complete?</th>
<th>Name</th>
<th></th>
<th></th>
</tr>
<tbody id="todos"></tbody>
</table>
<script src="js/site.js" asp-append-version="true"></script>
<script type="text/javascript">
getItems();
</script>
</body>
</html>
Tambahkan file CSS bernama site.css
ke folder wwwroot/css . Ganti konten site.css
dengan gaya berikut:
input[type='submit'], button, [aria-label] {
cursor: pointer;
}
#editForm {
display: none;
}
table {
font-family: Arial, sans-serif;
border: 1px solid;
border-collapse: collapse;
}
th {
background-color: #f8f8f8;
padding: 5px;
}
td {
border: 1px solid;
padding: 5px;
}
Tambahkan file JavaScript bernama site.js
ke folder wwwroot/js. Ganti isi site.js
dengan kode berikut:
const uri = 'api/todoitems';
let todos = [];
function getItems() {
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
}
function addItem() {
const addNameTextbox = document.getElementById('add-name');
const item = {
isComplete: false,
name: addNameTextbox.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getItems();
addNameTextbox.value = '';
})
.catch(error => console.error('Unable to add item.', error));
}
function deleteItem(id) {
fetch(`${uri}/${id}`, {
method: 'DELETE'
})
.then(() => getItems())
.catch(error => console.error('Unable to delete item.', error));
}
function displayEditForm(id) {
const item = todos.find(item => item.id === id);
document.getElementById('edit-name').value = item.name;
document.getElementById('edit-id').value = item.id;
document.getElementById('edit-isComplete').checked = item.isComplete;
document.getElementById('editForm').style.display = 'block';
}
function updateItem() {
const itemId = document.getElementById('edit-id').value;
const item = {
id: parseInt(itemId, 10),
isComplete: document.getElementById('edit-isComplete').checked,
name: document.getElementById('edit-name').value.trim()
};
fetch(`${uri}/${itemId}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(() => getItems())
.catch(error => console.error('Unable to update item.', error));
closeInput();
return false;
}
function closeInput() {
document.getElementById('editForm').style.display = 'none';
}
function _displayCount(itemCount) {
const name = (itemCount === 1) ? 'to-do' : 'to-dos';
document.getElementById('counter').innerText = `${itemCount} ${name}`;
}
function _displayItems(data) {
const tBody = document.getElementById('todos');
tBody.innerHTML = '';
_displayCount(data.length);
const button = document.createElement('button');
data.forEach(item => {
let isCompleteCheckbox = document.createElement('input');
isCompleteCheckbox.type = 'checkbox';
isCompleteCheckbox.disabled = true;
isCompleteCheckbox.checked = item.isComplete;
let editButton = button.cloneNode(false);
editButton.innerText = 'Edit';
editButton.setAttribute('onclick', `displayEditForm(${item.id})`);
let deleteButton = button.cloneNode(false);
deleteButton.innerText = 'Delete';
deleteButton.setAttribute('onclick', `deleteItem(${item.id})`);
let tr = tBody.insertRow();
let td1 = tr.insertCell(0);
td1.appendChild(isCompleteCheckbox);
let td2 = tr.insertCell(1);
let textNode = document.createTextNode(item.name);
td2.appendChild(textNode);
let td3 = tr.insertCell(2);
td3.appendChild(editButton);
let td4 = tr.insertCell(3);
td4.appendChild(deleteButton);
});
todos = data;
}
Perubahan pada pengaturan peluncuran proyek ASP.NET Core mungkin diperlukan untuk menguji halaman HTML secara lokal:
launchUrl
Hapus properti untuk memaksa aplikasi dibuka di index.html
—file default proyek.Sampel ini memanggil semua metode CRUD API web. Berikut ini adalah penjelasan tentang permintaan API web.
Dalam kode berikut, permintaan HTTP GET dikirim ke rute api/todoitems :
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
Ketika API web mengembalikan kode status yang berhasil, _displayItems
fungsi dipanggil. Setiap item yang harus dilakukan dalam parameter array yang diterima oleh _displayItems
ditambahkan ke tabel dengan tombol Edit dan Hapus . Jika permintaan API web gagal, kesalahan dicatat ke konsol browser.
Dalam kode berikut:
item
dinyatakan untuk membangun representasi harfiah objek dari item yang harus dilakukan.method
—menentukan kata kerja tindakan HTTP POST.body
—menentukan representasi JSON dari isi permintaan. JSON diproduksi dengan meneruskan literal objek yang disimpan ke item
fungsi JSON.stringify .headers
—menentukan Accept
header permintaan HTTP dan Content-Type
. Kedua header diatur ke application/json
untuk menentukan jenis media yang diterima dan dikirim, masing-masing.function addItem() {
const addNameTextbox = document.getElementById('add-name');
const item = {
isComplete: false,
name: addNameTextbox.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getItems();
addNameTextbox.value = '';
})
.catch(error => console.error('Unable to add item.', error));
}
Ketika API web mengembalikan kode status yang berhasil, getItems
fungsi dipanggil untuk memperbarui tabel HTML. Jika permintaan API web gagal, kesalahan dicatat ke konsol browser.
Memperbarui item yang harus dilakukan mirip dengan menambahkan item; namun, ada dua perbedaan signifikan:
method
oleh opsi .fetch(`${uri}/${itemId}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(() => getItems())
.catch(error => console.error('Unable to update item.', error));
Untuk menghapus item yang harus dilakukan, atur opsi permintaan method
ke DELETE
dan tentukan pengidentifikasi unik item di URL.
fetch(`${uri}/${id}`, {
method: 'DELETE'
})
.then(() => getItems())
.catch(error => console.error('Unable to delete item.', error));
Lanjutkan ke tutorial berikutnya untuk mempelajari cara membuat halaman bantuan API web:
Tutorial ini menunjukkan cara memanggil API web ASP.NET Core dengan JavaScript, menggunakan Fetch API.
Di bagian ini, Anda akan menambahkan halaman HTML yang berisi formulir untuk membuat dan mengelola item yang harus dilakukan. Penanganan aktivitas dilampirkan ke elemen di halaman. Penanganan aktivitas menghasilkan permintaan HTTP ke metode tindakan API web. Fungsi Fetch API fetch
memulai setiap permintaan HTTP.
Fungsi fetch
mengembalikan objek, yang berisi respons HTTP yang direpresentasikan Promise
sebagai Response
objek. Pola umumnya adalah mengekstrak isi respons JSON dengan memanggil json
fungsi pada Response
objek. JavaScript memperbarui halaman dengan detail dari respons API web.
Panggilan paling fetch
sederhana menerima satu parameter yang mewakili rute. Parameter kedua, yang init
dikenal sebagai objek, bersifat opsional. init
digunakan untuk mengonfigurasi permintaan HTTP.
Program.cs
:using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
var app = builder.Build();
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Buat folder wwwroot di akar proyek.
Buat folder css di dalam folder wwwroot .
Buat js folder di dalam folder wwwroot .
Tambahkan file HTML bernama index.html
ke folder wwwroot . Ganti konten index.html
dengan markup berikut:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>To-do CRUD</title>
<link rel="stylesheet" href="css/site.css" />
</head>
<body>
<h1>To-do CRUD</h1>
<h3>Add</h3>
<form action="javascript:void(0);" method="POST" onsubmit="addItem()">
<input type="text" id="add-name" placeholder="New to-do">
<input type="submit" value="Add">
</form>
<div id="editForm">
<h3>Edit</h3>
<form action="javascript:void(0);" onsubmit="updateItem()">
<input type="hidden" id="edit-id">
<input type="checkbox" id="edit-isComplete">
<input type="text" id="edit-name">
<input type="submit" value="Save">
<a onclick="closeInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Is Complete?</th>
<th>Name</th>
<th></th>
<th></th>
</tr>
<tbody id="todos"></tbody>
</table>
<script src="js/site.js" asp-append-version="true"></script>
<script type="text/javascript">
getItems();
</script>
</body>
</html>
Tambahkan file CSS bernama site.css
ke folder wwwroot/css . Ganti konten site.css
dengan gaya berikut:
input[type='submit'], button, [aria-label] {
cursor: pointer;
}
#editForm {
display: none;
}
table {
font-family: Arial, sans-serif;
border: 1px solid;
border-collapse: collapse;
}
th {
background-color: #f8f8f8;
padding: 5px;
}
td {
border: 1px solid;
padding: 5px;
}
Tambahkan file JavaScript bernama site.js
ke folder wwwroot/js. Ganti isi site.js
dengan kode berikut:
const uri = 'api/todoitems';
let todos = [];
function getItems() {
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
}
function addItem() {
const addNameTextbox = document.getElementById('add-name');
const item = {
isComplete: false,
name: addNameTextbox.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getItems();
addNameTextbox.value = '';
})
.catch(error => console.error('Unable to add item.', error));
}
function deleteItem(id) {
fetch(`${uri}/${id}`, {
method: 'DELETE'
})
.then(() => getItems())
.catch(error => console.error('Unable to delete item.', error));
}
function displayEditForm(id) {
const item = todos.find(item => item.id === id);
document.getElementById('edit-name').value = item.name;
document.getElementById('edit-id').value = item.id;
document.getElementById('edit-isComplete').checked = item.isComplete;
document.getElementById('editForm').style.display = 'block';
}
function updateItem() {
const itemId = document.getElementById('edit-id').value;
const item = {
id: parseInt(itemId, 10),
isComplete: document.getElementById('edit-isComplete').checked,
name: document.getElementById('edit-name').value.trim()
};
fetch(`${uri}/${itemId}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(() => getItems())
.catch(error => console.error('Unable to update item.', error));
closeInput();
return false;
}
function closeInput() {
document.getElementById('editForm').style.display = 'none';
}
function _displayCount(itemCount) {
const name = (itemCount === 1) ? 'to-do' : 'to-dos';
document.getElementById('counter').innerText = `${itemCount} ${name}`;
}
function _displayItems(data) {
const tBody = document.getElementById('todos');
tBody.innerHTML = '';
_displayCount(data.length);
const button = document.createElement('button');
data.forEach(item => {
let isCompleteCheckbox = document.createElement('input');
isCompleteCheckbox.type = 'checkbox';
isCompleteCheckbox.disabled = true;
isCompleteCheckbox.checked = item.isComplete;
let editButton = button.cloneNode(false);
editButton.innerText = 'Edit';
editButton.setAttribute('onclick', `displayEditForm(${item.id})`);
let deleteButton = button.cloneNode(false);
deleteButton.innerText = 'Delete';
deleteButton.setAttribute('onclick', `deleteItem(${item.id})`);
let tr = tBody.insertRow();
let td1 = tr.insertCell(0);
td1.appendChild(isCompleteCheckbox);
let td2 = tr.insertCell(1);
let textNode = document.createTextNode(item.name);
td2.appendChild(textNode);
let td3 = tr.insertCell(2);
td3.appendChild(editButton);
let td4 = tr.insertCell(3);
td4.appendChild(deleteButton);
});
todos = data;
}
Perubahan pada pengaturan peluncuran proyek ASP.NET Core mungkin diperlukan untuk menguji halaman HTML secara lokal:
launchUrl
Hapus properti untuk memaksa aplikasi dibuka di index.html
—file default proyek.Sampel ini memanggil semua metode CRUD API web. Berikut ini adalah penjelasan tentang permintaan API web.
Dalam kode berikut, permintaan HTTP GET dikirim ke rute api/todoitems :
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
Ketika API web mengembalikan kode status yang berhasil, _displayItems
fungsi dipanggil. Setiap item yang harus dilakukan dalam parameter array yang diterima oleh _displayItems
ditambahkan ke tabel dengan tombol Edit dan Hapus . Jika permintaan API web gagal, kesalahan dicatat ke konsol browser.
Dalam kode berikut:
item
dinyatakan untuk membangun representasi harfiah objek dari item yang harus dilakukan.method
—menentukan kata kerja tindakan HTTP POST.body
—menentukan representasi JSON dari isi permintaan. JSON diproduksi dengan meneruskan literal objek yang disimpan ke item
fungsi JSON.stringify .headers
—menentukan Accept
header permintaan HTTP dan Content-Type
. Kedua header diatur ke application/json
untuk menentukan jenis media yang diterima dan dikirim, masing-masing.function addItem() {
const addNameTextbox = document.getElementById('add-name');
const item = {
isComplete: false,
name: addNameTextbox.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getItems();
addNameTextbox.value = '';
})
.catch(error => console.error('Unable to add item.', error));
}
Ketika API web mengembalikan kode status yang berhasil, getItems
fungsi dipanggil untuk memperbarui tabel HTML. Jika permintaan API web gagal, kesalahan dicatat ke konsol browser.
Memperbarui item yang harus dilakukan mirip dengan menambahkan item; namun, ada dua perbedaan signifikan:
method
oleh opsi .fetch(`${uri}/${itemId}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(() => getItems())
.catch(error => console.error('Unable to update item.', error));
Untuk menghapus item yang harus dilakukan, atur opsi permintaan method
ke DELETE
dan tentukan pengidentifikasi unik item di URL.
fetch(`${uri}/${id}`, {
method: 'DELETE'
})
.then(() => getItems())
.catch(error => console.error('Unable to delete item.', error));
Lanjutkan ke tutorial berikutnya untuk mempelajari cara membuat halaman bantuan API web:
Umpan balik ASP.NET Core
ASP.NET Core adalah proyek sumber terbuka. Pilih tautan untuk memberikan umpan balik:
Acara
19 Nov, 23 - 21 Nov, 23
Bergabunglah dengan sesi online di Microsoft Ignite yang dibuat untuk memperluas keterampilan Anda dan membantu Anda mengatasi masalah kompleks saat ini.
Daftar sekarang