在此微調我們的ProductController
將ProductDetailsModel多增加一個Price屬性
更改Details Action要返回的資料Model
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MyReact1.Controllers
{
// -> /api/Product
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
public IActionResult List()
{
var model = new ProductModel
{
Products = new List<ProductModel.ProductListItem> {
new ProductModel.ProductListItem{Id = 1, Name = "The first", Description="product 1"}
}
};
return Ok(model);
}
// -> /api/Product/10
[HttpGet("{id}")]
public IActionResult Details(int id)
{
return Ok(new ProductDetailsModel
{
Id = id,
Name = "A product",
Description = "Description",
Price = 1000
});
}
}
public class ProductModel
{
public List<ProductListItem> Products { get; set; } = new List<ProductListItem>();
public class ProductListItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
public class ProductDetailsModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
再到
~\ClientApp\src\components\ProductDetail.js
引入Axios來進行API存取
import React, { Component } from 'react';
import Axios from 'axios';
export default class ProductDetails extends Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
let result = await Axios(`https://localhost:7247/api/product/${this.props.match.params.id}`);
this.setState(result.data);
}
render() {
return <div className="row">
<div className="col-12">
<div className="media">
<img src="https://via.placeholder.com/600" className="mr-3" alt="Product" />
<div className="media-body">
<h1>{this.state.name}</h1>
<p>{this.state.description}</p>
<p>£{this.state.price}</p>
</div>
</div>
</div>
</div>
}
}
在此可針對js偵錯觀察回傳結果
最終就可以成功資料綁定於頁面中