I have a Razor Page and in the HTML there's a list of buttons and I want to be able to change the class list on those buttons to highlight the currently selected one. Each button looks like so:
<form asp-page-handler="Posts" method="post">
<button href="posts" class="nav-link text-white active" aria-current="page">
Posts
</button>
</form>
When it is clicked it will call a handler method and I want to add the active class to it and remove the active class from the previous one. This would be trivial in javascript and maybe it is in c# but after an hour of searching, I can't find a way to do this.
Here is a working demo to add the active class to selected button without js: cshtml.cs:
[BindProperty]
public List<Button> buttons { get; set; }
public void OnGet()
{
buttons = new List<Button> { new Button { Id = 1, Content = "button1" }, new Button { Id = 2, Content = "button2"}, new Button { Id = 3, Content = "button3" } };
public IActionResult OnPostPosts(int id)
{
buttons.ForEach(b => b.IsActive = false);
buttons.Where(b => b.Id == id).ToList().ForEach(b => b.IsActive = true);
//save data to database,add data to gridBind
return Page();
}
}
Button.cs:
public class Button {
public int Id { get; set; }
public string Content { get; set; }
public bool IsActive { get; set; }
}
View:
<form method="post">
@for (var i = 0; i < Model.buttons.Count; i++)
{
<input hidden name="buttons[@i].Id" [email protected][i].Id />
<input hidden name="buttons[@i].Content" [email protected][i].Content />
<input hidden name="buttons[@i].IsActive" [email protected][i].IsActive />
}
@foreach (var item in Model.buttons)
{
<input type="submit" asp-page-handler="Posts" asp-route-id="@item.Id" class="nav-link text-white @(item.IsActive ? "active" : "")" aria-current="page" value="@item.Content" />
}
</form>