Learn the process of updating database information with AngularJS through a button click

As a newcomer to Angular, I am facing an issue in my mini project. The main goal of the project is to display data from a database. I have successfully set up the view to show current data by making API calls and connecting to the database. However, I am now trying to figure out how to update the data in the database when a button is clicked. I'm unsure of what kind of function I should write in my controller for this task.

var app = angular.module('myApp', ['ngResource']);
app.controller('myCtrl', function ($scope, $resource, $http, $routeParams, $location) {

    var Users = $resource('/api/tables');
    $scope.users = Users.query(function () {
        //console.log(user);
    });
});

In my (API) Tables1Controller.cs file, here is the main method:

public string GetTables()
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(db.Tables);
        } 

And in my Index file where the data is displayed, I have added a button:

<table class="table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Surname</th>
            <th>Address</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
            <td>{{user.Id}}</td>
            <td>{{user.Name}}</td>
            <td>{{user.Surename}}</td>
            <td>{{user.Address}}</td>
        </tr>
    </tbody>
</table>

<div ng-repeat=>
    {{ user.Name }}
    a
</div>
<div class="btn btn-danger">Button</div>

In _Layout.cshtml, I have added ng-app and ng-controller to the body tag. I believe using ng-click near the button could be a starting point, but I'm unfamiliar with how to write the function to handle the update process.

Answer №1

It appears that you are utilizing ASP.Net MVC in conjunction with Angular. It can be tricky because the term 'controller' carries different meanings in the context of MVC and Angular.

To address your question, there are two key steps to follow:

  1. Angular: Utilize $http.post to send data when the button is clicked by the user. Make sure that the URL specified in $http.post matches the route defined in step #2.
  2. MVC controller: Create a HttpPost controller to receive data from the browser. Then execute an insert command to store the data in your storage system.

Answer №2

Issue Resolved!

I made a modification to the js file:

$scope.update = (function () {
        var Users = $resource('/api/tables');
        $scope.users = Users.query(function () {
        });
    });

Additionally, I added a button in the html file like this:

<div class="btn btn-success" ng-click="update()">Update</div>

Answer №3

For further information, check out this article on ngResource:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Numerous Axios GET calls made by various components

I am facing an issue where I have two different components rendering on the main screen. Both of them make multiple axios.get requests to fetch data. However, upon initial page load, only the last component successfully retrieves the data while the first c ...

The @Input() property within an Angular component is producing an empty array as its result

I have a calendar component that has a data property marked as @Input(): import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-calendar', templateUrl: './calendar.comp ...

Incorporating a new dropdown menu above the content of a pre-existing jQuery accordion dropdown, causing the content to shift downwards

Seeking a way to overlay a second-level dropdown menu on top of the content beneath a jQuery accordion-style dropdown. Typically, the jQuery accordion pushes down the content below, but I want the second-level dropdown to remain unaffected. Is there a solu ...

What is the approach for capturing system or website sound using JavaScript?

After creating an online drumkit and guitar player, I am now looking to enhance my website by adding a feature that allows users to record their sessions and download them. Since I am new to web development and familiar only with HTML, CSS, JavaScript, and ...

Activating JavaScript in the browser only when a button is manually clicked, not by default

As I work on my website, which is currently being constructed, I rely heavily on JavaScript. However, a concern of mine is the potential for failure if a user has JavaScript disabled on their client side system. I understand that it is not possible to pro ...

Issue: the size of the requested entity is too large

Encountering an error message while using express: Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Users/ ...

"Prevent further button clicks by disabling it after the initial click with ActionRowBuilder in Discord.Js

Encountering a puzzling issue where I am unable to disable a button after it has been clicked. The option to disable the button does not seem to appear. When attempting to deactivate the button, I utilize the following function: const row = new ActionRowBu ...

How come the use of a timeout causes the this variable to seemingly lose its reference?

What is the reason why this: myelements.mouseenter(function() { clearTimeout(globaltimeoutvar); globaltimeoutvar = setTimeout(function() { var index = myelements.index(this); console.log(index); // -1 }, 150); }); Returns -1, while this: m ...

Learn how to showcase a modal pop-up in AngularJS by utilizing the ng-if directive

Hello, I am new to working with AngularJS. My question is how can I display a modal pop-up box when the ng-if statement evaluates to false? Can you please provide guidance on how to solve this issue? Here is an example of the code snippet in HTML: <di ...

Successfully received response from Ajax post - unable to display on screen

After successfully posting data to the server using $.post(), I am encountering issues when trying to work with the response. Unfortunately, nothing appears - no console log is shown and I am unable to replace text or HTML with the retrieved data. Below i ...

Converting human-readable dates into a Date object

How can I reliably convert human-entered dates into a Date() object for my project that utilizes a ML text extractor? Although seemingly straightforward, the issue lies in the wide variety of formats used by individuals when entering dates, ranging from " ...

What is the reason behind needing to restart the server each time I make a change to my React application?

I'm diving into my first project using React, stepping away from my usual tools of pure HTML, JavaScript, PHP, and Node.js. I decided to create a single-page application portfolio, but I've encountered a frustrating issue. Every time I make a cha ...

Error validation for jQuery div dropdown

Can jQuery validation be used to set the required attribute on a Bootstrap styled div dropdown instead of an option/select tag? The tags cannot be changed on this page, and there are multiple div dropdowns. <div class="btn-group"> <button typ ...

transferring data from HTML to JavaScript functions

I am facing an issue with my ng-repeat in the view where I want to pass the object from the ng-repeat to a javascript function. However, when I attempt to display it on the console, it shows up as undefined. Below is the HTML code snippet: <!-- Panel ...

How to Monitor Store Changes within a Vue File Using Vue.js

I am working with 2 vue files, header.vue and sidebar.vue. Both components are imported into layout.vue. Here are the steps I am following: 1. Initially, when the page loads, I update the store in header.vue with some values inside the created hook. 2. ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

Vue Material - Effortlessly integrate native transitions within router views

In the project I'm currently working on, I have chosen to use Vue Material for the development of a single-page application. The approach I am taking follows a common trend in which a central "container" component is utilized to manage the shifting vi ...

Updating the chosen option using jQuery

Is there a way to change the currently selected option using jQuery? <select name="nameSelect" id="idSelect"> <option value="0">Text0</option> <option value="1">Text1</option> <option value="2" selected>Text ...

Element remains hidden until the developer console is activated

On my website, I've noticed that certain LayerSlider elements are remaining invisible until: The window is resized I disable the Bookmarks bar in Chrome (quite strange, right?) I switch on the Chrome debugger tools This issue is not exclusive to Ch ...

Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize thi ...