ASP.NET Core MVC with React
Hello this time I will try to share my exploration make Application ASP.NET Core MVC with React,
Prerequisites
Step 1
we need to make our project
then choose a template
here I choose React and ASP.NET Core (Preview)
we can set our Project Name and where we will put the aplication
After a while our project will be created, there we have well structured Back End and Front End project.
We can try to run our project.
it will show us default project, let's see where this data come from
the data is dummy data that come from WeatherForecastControllers on the Back End that then fetched using the code on App.jsx on the Front End
async populateWeatherData() {
const response = await fetch('weatherforecast');
const data = await response.json();
this.setState({ forecasts: data, loading: false });
}
Step 2
Now we will try to mimic that, I will make the Back End similar to what I do on this Article that I create previously, I just make a little adjustment on the program.cs
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp", builder => builder
.WithOrigins("https://localhost:5173") // Replace with your React app's origin
.AllowAnyHeader()
.AllowAnyMethod());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseDefaultFiles();
app.UseStaticFiles();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowReactApp");
app.UseAuthorization();
app.MapControllers();
app.Run();
on that code I also add cors settings.
after test that the Back End is indeed works we can start working on the Front End
Step 3
Now we sill start working on Front End, install 'axios' on our react project
we can do using
npm install axios
or install it on solution explorer Visual Studio
just search packages that you need to install
check on package.json to make sure that the package is already installed
Create new file on src folder,
import { Component } from 'react';
import axios from 'axios';
class FoodList extends Component {
constructor(props) {
super(props);
this.state = {
foodData: [],
loading: true,
};
}
componentDidMount() {
// Define the API URL
const apiUrl = 'https://localhost:7224/api/food';
// Use Axios to fetch data from the API
axios.get(apiUrl)
.then(response => {
// Update the component's state with the fetched data
this.setState({
foodData: response.data,
loading: false,
});
})
.catch(error => {
console.error('Error fetching data:', error);
this.setState({ loading: false });
});
}
render() {
const { foodData, loading } = this.state;
return (
<div>
<h1>Food Menu</h1>
{loading ? (
<p>Loading... Please wait.</p>
) : (
<ul>
{foodData.map(food => (
<li key={food.foodId}>
<strong>{food.name}</strong> - {food.description} (${food.price})
</li>
))}
</ul>
)}
</div>
);
}
}
export default FoodList;
this code is fetching the data from endpoint 'https://localhost:7224/api/food',
and then display it on list, save the file then open App.jsx
import the file that just we make
import FoodList from './pages/FoodList';
then put it below default table
<div>
<FoodForm />
</div>
save the file then we can see new list of Food from our database.
For simplicity I make the design and code as simple as possible, the rest of code will I update on my Github ?
Thanks for your attention. I hope this toturial is useful See you ??