The main objectives of this article are:
(Step 3)
In the next article, we are going to implement DELETE Operation.
- Create Get By Id Endpoint In API Project.
- Create An Update Endpoint In The API Project.
- Create VueJS Component To Display Update Form.
Create Get By Id Endpoint In API Project:
To update any record, we first need to fetch the record by its 'id'. So let's create a get by 'id' endpoint in our API project.
API_Project/Controllers/BeachController.cs:
[HttpGet] [Route("{id:int}")] public async Task<IActionResult> Get(int id) { var becahById = await _myWorldDbContext.Beach.Where(_ => _.Id == id) .FirstOrDefaultAsync(); return Ok(becahById); }
- (Line: 1) Since it is a second HTTP Get action method, so we have to explicitly specify the route.
- (Line: 2) The route expression '{id:int}' represents 'id' value must be the integer value.
- (Line: 5) Fetching the record by 'id' from the database.
Create An Update Endpoint In The API Project:
Let's create the HTTP PUT action method.
API_Project/Controllers/BeachController.cs:
[HttpPut] public async Task<IActionResult> Put(Beach beachToUpdate) { _myWorldDbContext.Beach.Update(beachToUpdate); await _myWorldDbContext.SaveChangesAsync(); return Ok(beachToUpdate); }
- (Line: 1) The 'HttpPut' verb makes our action method can be accessed by the HTTP PUT requests.
- (Line: 2) Here to the action method we are passing our record that needs to be updated. In this payload, the 'id' value should be mandatory.
- (Line: 4) Using the 'Update' method attach our payload data to the database context.
- (Line: 5) Using the 'SaveChangesAsync()' method save our changes to the database.
Create An 'EditBeach' Component In VueJS App:
Let's create a new VueJS component like 'EditBeach' to handle the update form.
Now add routing for our 'EditBeach.vue' component.Vue_App/src/router/index.js:
import { createRouter, createWebHistory } from 'vue-router' import EditBeach from '../views/beaches/EditBeach.vue' // existing code hidden for display purpose const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path:'/edit/:id', name:'edit-beach', component: EditBeach } ] }) export default router
- Here ':id' is the dynamic placeholder, where we pass 'id' value into the route for navigation.
Implement Update Form Logic:
Let's implement the update form logic in the 'EditBeach.vue' component.
Vue_App/src/views/beaches/EditBeach.vue:
<script setup> import axios from "axios"; import { reactive, onMounted } from "vue"; import { useRouter, useRoute } from "vue-router"; let beachToUpdate = reactive({ id: 0, beachName: "", place: "", imageUrl: "", }); const router = useRouter(); const route = useRoute(); onMounted(() => { axios .get(`http://localhost:5247/Beach/${route.params.id}`) .then((response) => { beachToUpdate.id = response.data.id; beachToUpdate.beachName = response.data.beachName; beachToUpdate.place = response.data.place; beachToUpdate.imageUrl = response.data.imageUrl; }); }); const updateBeach = () => { axios.put("http://localhost:5247/Beach", beachToUpdate).then(() => { router.push("/"); }); }; </script> <template> <div class="container mt-4"> <form @submit.prevent="updateBeach"> <legend>Update Beach & It's Location</legend> <div class="mb-3"> <label for="txtBeachName" class="form-label">Beach Name</label> <input type="text" v-model="beachToUpdate.beachName" class="form-control" id="txtBeachName" /> </div> <div class="mb-3"> <label for="txtPlace" class="form-label">Place</label> <input type="text" v-model="beachToUpdate.place" class="form-control" id="txtPlace" /> </div> <div class="mb-3"> <label for="txtImageUrl" class="form-label">Image URL</label> <input type="text" v-model="beachToUpdate.imageUrl" class="form-control" id="txtImageUrl" /> </div> <button type="submit" class="btn btn-primary">Add</button> </form> </div> </template>
- (Line: 1) The 'setup' attribute added to the script tag that represents we are using the composition API approach.
- (Line: 6-11) The 'reactive' type loads from the 'vue' library. The 'reactive' type is appropriate for creating the model for the form binding in Vue. Here we defined properties like 'id', 'beachName', 'place' and 'imageUrl' which can use for form binding.
- (Line: 13) The 'useRouter' loads from 'vue-router' library that helps for navigation.
- (Line: 14) The 'useRoute' loads from the 'vue-router' library that helps to read the URL parameters
- (Line: 16-25) The 'onMounted' is vue life-cycle method in which we invoke the get by 'id' endpoint to populate the item data into our update form.
- (Line: 27-31) Here we defined method like 'updateBeach' that contains logic to invoke the HTTP PUT request to update the item.
- In vue enable the form model binding we will use 'v-model' attribute. Each form field must decorate with 'v-model'.
- (Line: 35) The '@submit.prevent' event raises on clicking the form submit button, but it won't reload the page since we configured the 'prevent' event. Here '@submit.prevent' is registered with 'updateBeach' method.
Vue_App/src/views/beaches/BeachList.vue:
<div class="card-body"> <h5 class="card-title">{{ item.beachName }}</h5> <p class="card-text">Location: {{ item.place }}</p> <router-link class="btn btn-primary" :to="`/edit/${item.id}`">Edit</router-link> </div>
- (Line: 4) The 'router-link' is a vue router default component that will render as anchor tag. Here for 'to' attribute we assigned our navigation url.
(Step 3)
In the next article, we are going to implement DELETE Operation.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on the .NET 7 Web API and Vue(3.0) application. using I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment