Simple Vue.js Frontend with C# Backend App
Here's a basic application with a Vue.js frontend and a C# backend. This example will create a simple task management app where you can add and view tasks.
Backend (C# ASP.NET Core)
1. Create the backend project
bash Copy code
dotnet new webapi -n TaskManagerBackend
cd TaskManagerBackend
2. Install required packages
bash Copy code
dotnet add package Microsoft.EntityFrameworkCore.InMemory
3. Update Program.cs
csharp Copy code
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<TaskDbContext>(opt => opt.UseInMemoryDatabase("TaskList"));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
// Database context
public class TaskDbContext : DbContext
{
public TaskDbContext(DbContextOptions<TaskDbContext> options) : base(options) { }
public DbSet<TaskItem> Tasks => Set<TaskItem>();
}
// Task model
public class TaskItem
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsCompleted { get; set; }
}
// Controller
[ApiController]
[Route("api/[controller]")]
public class TasksController : ControllerBase
{
private readonly TaskDbContext _context;
public TasksController(TaskDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<TaskItem>>> GetTasks()
{
return await _context.Tasks.ToListAsync();
}
[HttpPost]
public async Task<ActionResult<TaskItem>> PostTask(TaskItem task)
{
_context.Tasks.Add(task);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetTasks), new { id = task.Id }, task);
}
}
Frontend (Vue.js)
1. Create the frontend project
bash Copy code
npm init vue@latest task-manager-frontend
cd task-manager-frontend
npm install
npm install axios
2. Update src/App.vue
vue Copy code
<template>
<div id="app">
<h1>Task Manager</h1>
<div>
<input v-model="newTask" @keyup.enter="addTask" placeholder="Add a new task">
<button @click="addTask">Add</button>
</div>
<ul>
<li v-for="task in tasks" :key="task.id">
<input type="checkbox" v-model="task.isCompleted" @change="updateTask(task)">
<span :class="{ completed: task.isCompleted }">{{ task.title }}</span>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'App',
data() {
return {
tasks: [],
newTask: ''
}
},
created() {
this.fetchTasks();
},
methods: {
async fetchTasks() {
try {
const response = await axios.get('https://localhost:5001/api/tasks');
this.tasks = response.data;
} catch (error) {
console.error('Error fetching tasks:', error);
}
},
async addTask() {
if (this.newTask.trim() === '') return;
try {
const response = await axios.post('https://localhost:5001/api/tasks', {
title: this.newTask,
isCompleted: false
});
this.tasks.push(response.data);
this.newTask = '';
} catch (error) {
console.error('Error adding task:', error);
}
},
async updateTask(task) {
try {
await axios.put(`https://localhost:5001/api/tasks/${task.id}`, task);
} catch (error) {
console.error('Error updating task:', error);
}
}
}
}
</script>
<style>
.completed {
text-decoration: line-through;
color: #888;
}
</style>
3. Update src/main.js
javascript Copy code
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
Running the Application
Backend
Run the backend:
The backend will be available at https://localhost:5001
Frontend
Run the frontend:
The frontend will be available at http://localhost:5173 (or similar port)
Features
Add new tasks by typing in the input field and pressing Enter or clicking Add
Mark tasks as completed by checking the checkbox
Tasks are stored in memory (will reset when the backend restarts)
Next Steps
Add proper error handling
Implement task deletion
Add persistence (replace InMemoryDatabase with a real database)
Add authentication
Improve the UI with a proper styling framework
This is a basic example to get you started with a Vue.js frontend and C# backend. You can expand it based on your requirements.