'How to dynamically change background-color in ASP.NET MVC core?

I had an idea of changing a background color of a div when I click a button. I added a string in my 'Subject' model class as so:

[NotMapped]
public string ColorHEX { get; set; }

And made an action inside of a controller as so:

        [HttpGet]
        public IActionResult ChangeColor(int id)
        {
            Subject subject = _context.Subjects.Find(id);
            return View(subject);
        }
        [HttpPost]
        public IActionResult ChangeColor(Subject subject, string color)
        {
            subject.ColorHEX = color;

            _context.Update(subject);
            _context.SaveChanges();
            return View();
        }

And the post View:

@model Subject;

<form asp-action="ChangeColor" method="post">
    <input type="submit" value="#1e1e1e;" name="color" />
</form>

It correctly transfers the color value to the controller parameter string color, and it stores it inside the ColorHEX variable.

And my idea was to implement it in an inline style of a div inside the foreach loop. Like so:

@model IEnumerable<EVE_A_Planner.Models.Subject>

@{
    ViewData["Title"] = "AllTasks";
}
<div class="container">
    <h1 class="d-flex justify-content-center">My Tasks</h1>

    <div class="row">
        @foreach (var item in Model)
        {
            <div class="mySkillsBox" style="background-color: @item.ColorHEX">
                <div class="row">
                    <div class="col">
                        <div>
                            <img class="mySkillsImage" [email protected] width="200">
                        </div>
                    </div>
                </div>
            </div>
        }
    </div>
</div>

When I try this, nothing happens... Any ideas how to implement this? Thanks!



Solution 1:[1]

    [HttpPost]
    public IActionResult ChangeColor(Subject subject, string color)
    {
        subject.ColorHEX = color;

        _context.Update(subject);
        _context.SaveChanges();
        return View();// do somethings as below...
    }

Check with your post action.

First, you should query the database to get the latest subject data .

Second, you have two options:

  1. You can return the latest subject data to the ChangeColor view.

2.Redirect to the Index action, in the Index action, get the latest subject data from database, and then return to the view(In the Index View, you can implement it in an inline style of a div inside the foreach loop ).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Qing Guo