Skip to content

Sending Data from Vue.js to C# REST API with Dapper: A Practical Approach

The other day, I faced a task in a project where I had to send data from a Vue.js frontend to a C# backend. You know, sometimes you think it’s simple, but once you get into it, you realize it’s not such a straightforward process. Usually, in such cases, we either send data directly via an HTTP POST or use solutions like SignalR, which I’ve used before. But this time, things were different. We needed to connect to a REST API, and on the backend, we had a setup with Dapper connecting to PostgreSQL. So, what do we do in such situations? That’s where some thinking is required.

Meanwhile, I remembered a simple proxy program I wrote a few years ago. It was for bypassing filters when trying to access blocked sites, like breaking TTnet’s filters. That program was also based on managing HTTP requests. Funny enough, that program didn’t work this time; my own code failed 🙂 Anyway, back to the topic. On the Vue.js side, things are quite standard. We get data from a component or service layer, convert it to JSON format, and send it via a POST request. I think this process is similar across most frameworks. The real work begins on the backend.

On the backend, I set up an ASP.NET Core Web API project. Dapper was ready, and the PostgreSQL connection was configured. Now, we need to create a controller action that will accept JSON data from Vue.js. The data will then be sent directly to PostgreSQL using Dapper’s ExecuteAsync method. This will be a simple INSERT operation. However, security and validation are also important. You can’t trust all incoming data, right?

Let’s imagine an example. Suppose there is a user profile form in Vue.js. This form contains fields like username, email, and perhaps a password. We send this data to the backend, which saves it into a ‘Users’ table. Of course, this is a very basic example. In real projects, passwords are never sent or stored in plain text. Hashing and salting are essential. But for concept explanation, this example suffices.

First, let’s make a fetch call on the Vue.js side. With a simple POST method, we set the Content-Type header to application/json, and send the data as a JSON string using JSON.stringify.

// Inside Vue.js component or a service file async function saveUserData(userData) {   try {     const response = await fetch('/api/users', {       method: 'POST',       headers: {         'Content-Type': 'application/json'       },       body: JSON.stringify(userData)     });

if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }

const result = await response.json(); console.log(‘User successfully saved:’, result); return result; } catch (error) { console.error(‘Error occurred while saving user:’, error); } }

That’s it! This is the Vue.js side. Now, let’s move on to C#.

In the backend, we create a UsersController and add a Post action. This action will accept JSON from Vue and save it to PostgreSQL with Dapper.

Start by defining our database model. A simple User class is enough.

// Models/User.cs public class User {     public int Id { get; set; } // Auto-increment primary key     public string Username { get; set; }     public string Email { get; set; } }

Then, create the controller. Don’t forget to get the connection string from appsettings.json. I think it costs around 15-20 euros, just for reference 🙂 For this example, I’ll hardcode the connection string, but you should configure it properly.

Remember to add the Dapper NuGet package to your project for database operations.

// Controllers/UsersController.cs using Dapper; using Microsoft.AspNetCore.Mvc; using System.Data; using Npgsql; // PostgreSQL [ApiController] [Route("api/[controller]")] public class UsersController : ControllerBase {     private readonly string _connectionString; // read from appsettings.json     public UsersController(IConfiguration configuration)     {         _connectionString = configuration.GetConnectionString("DefaultConnection");     }     [HttpPost]     public async Task<IActionResult> PostUser([FromBody] User user)     {         if (user == null || string.IsNullOrWhiteSpace(user.Username) || string.IsNullOrWhiteSpace(user.Email))         {             return BadRequest("Invalid user data.");         }         using (IDbConnection db = new NpgsqlConnection(_connectionString))         {             var sql = @"INSERT INTO Users (Username, Email) VALUES (@Username, @Email); SELECT CAST(SCOPE_IDENTITY() as INT);";             try             {                 var newUserId = await db.QuerySingleAsync<int>(sql, user);                 return CreatedAtAction(nameof(GetUser), new { id = newUserId }, user);             }             catch (Exception ex)             {                 return StatusCode(500, $"Database error occurred: {ex.Message}");             }         }     }     [HttpGet("{id:int}")]     public async Task<IActionResult> GetUser(int id)     {         using (IDbConnection db = new NpgsqlConnection(_connectionString))         {             var sql = "SELECT * FROM Users WHERE Id = @Id;";             var user = await db.QuerySingleOrDefaultAsync<User>(sql, new { Id = id });             if (user == null)             {                 return NotFound();             }             return Ok(user);         }     } }

That’s all! We saw how to send data from Vue.js to C# with Dapper and PostgreSQL. This was just a simple INSERT operation. You can similarly implement update and delete operations. The key is to structure the JSON correctly on the frontend and handle it properly on the backend.

Ultimately, such integrations are fundamental in software development. Understanding both frontend and backend helps build seamless systems. Sometimes, complex-looking problems are actually solved with simple logic. That was one of those cases. Although real projects may be more complicated, the core logic remains the same.

And remember, Dapper’s performance is noteworthy. It’s faster than ORM tools and excels in simple queries, offering a real performance advantage when used correctly. Instead of trying to do everything with Dapper, use it where appropriate. In conclusion, Vue.js and Dapper can make data transfer processes very efficient, and it works smoothly.

If you’re interested, you can check Dapper’s official site. I don’t remember the exact link, but searching for “Dapper ORM” on Google should help.

My own program failed, but we created a nice project with Dapper this time 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.