Home > OS >  How to update all rows of a table in database using one Action method (ASP.NET)?
How to update all rows of a table in database using one Action method (ASP.NET)?

Time:03-10

I want to create a button such that if I click on it, it changes the entire column of a table in database. Please consider the code below:

Model:

using Player_Simulation.Data;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Player_Simulation.Models
{
    public class Player
    {
        public int PlayerId { get; set; }
        public string PlayerName { get; set; }
        public int PlayerRating { get; set; }
        public int PlayerYear { get; set; }
        public int PlayerSkill { get; set; }
        public string PlayerCountry { get; set; }
        public ICollection<Match> Matches { get; set; } 

        public Player()
        {
            PlayerYear = 1;
            PlayerRating = 1000;
        }
    }
}

Controller:

namespace Player_Simulation.Controllers
{
    public class PlayerController : Controller
    {
        private readonly DataContext _database;

        public PlayerController(DataContext database)
        {
            _database = database;
        }

        [HttpPost]
        public void IncrementYear()
        {
            using (_database)
            {
                foreach (Player player in _database.Players)
                {
                    if (player != null)
                    {
                        int oldYear = player.PlayerYear;
                        player.PlayerYear = oldYear   1;
                        _database.SaveChanges();
                    }
                }
            }
        }
    }
}

View:

// removed code for shorter post
// the button to click so I can increment the 'year' column by 1
<a asp-controller="Player" asp-action="IncrementYear" >Increment Year</a>

Graphics: enter image description here

Ultimately, I want a button that can increment all the years by 1. It does not need to return a View or anything like that. However, after referring to: enter image description here

  • Related