I recently sat and had a chat with a friend, you know how fast technology advances these days, sometimes it’s hard to keep up. He works with Vue.js for the frontend, and I work with C# and PostgreSQL for the backend. During our chat, we wondered how to send data from Vue.js to C# in the cleanest way. Sometimes I get stuck or my program hits a dead end 🙂 Naturally, I jumped in to explore this.
The logic is actually simple. The frontend, which is the Vue.js application, sends a request to the backend, including the data it wants to send. The backend receives this request, processes the data, and does whatever is required. Pretty straightforward, right? But when you get into the details, many things come up. For example, what data format should be used? JSON or form-data? Which HTTP method should be used? GET or POST? POST makes more sense because we are sending data, right?
One of my favorite approaches here is RESTful APIs. In C# with ASP.NET Core, we can develop robust REST APIs. When Dapper is involved, our database operations are both fast and clean. I really like Dapper because you can write SQL queries directly, and its performance is incredible. It’s almost like talking directly to the database.
Now, let’s move to the practical part. Suppose we are creating a user registration. On the frontend, using Vue.js, we have a form to collect user information like username and email. We prepare these details as a JavaScript object and send it via a POST request to the backend. On the backend, we will have a controller action to handle this request. This action will accept the incoming JSON data, deserialize it into a C# model, and then save it to the database using Dapper.
Isn’t that great? By the way, I don’t remember exactly, but there are some popular libraries for such requests on the frontend side. For example, Axios. Axios is Promise-based an HTTP client and very easy to use. When sending data as JSON, don’t forget to set the Content-Type header to `application/json`.
Let me show you how to do this with some simple code. Imagine:
// Vue.js Frontend (JavaScript) async function saveUser(userInfo) { try { const response = await axios.post('/api/users', userInfo, { headers: { 'Content-Type': 'application/json' } }); console.log('Registration successful:', response.data); return response.data; } catch (error) { console.error('Registration error:', error); throw error; } }
This code takes the `userInfo` object and sends it via a POST request to the `/api/users` endpoint. We also specified the Content-Type. Very simple.
Now, let’s see how to handle this request on the C# backend. Sometimes I forget the exact details when I try it myself 🙂 Dapper comes into play here.
// C# Backend (ASP.NET Core Controller) [HttpPost("/api/users")] public async Task<IActionResult> SaveUser([FromBody] UserModel user) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // Save to database with Dapper using (var connection = new SqlConnection("Your connection string")) // Remember to put your connection string :) { var sql = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)"; await connection.ExecuteAsync(sql, user); }
return Ok(new { message = "User successfully saved." }); }
// UserModel (Simple POCO) public class UserModel { public string Name { get; set; } public string Email { get; set; } }
Here, `[FromBody]` attribute is important as it binds the incoming JSON to the `UserModel`. Then, we execute a simple `INSERT` query with Dapper. Make sure your connection string is correct, or things can get messy. Sometimes it’s overlooked.
Isn’t it nice? Even a simple operation like this involves many behind-the-scenes mechanisms. Once you learn these basic steps, other data transfer methods become much easier. For instance, sometimes you might need to send data via form-data, but generally, I find JSON more convenient.
Meanwhile, error handling is very important. Using `try-catch` blocks on the frontend, `ModelState.IsValid` checks on the backend. Otherwise, the program could crash or behave unexpectedly with invalid data. I once made this mistake in one of my own projects, and it was a serious issue. Anyway, ultimately, establishing a solid bridge between these two worlds is crucial for both user experience and system stability.
If you want to see more details, you can check Dapper’s official documentation, which is very informative. Or, you can search Google for how to make API requests with Vue.js and Axios, you’ll find plenty of resources. There are also good tutorials on YouTube, for example, search example.