简体   繁体   中英

Reacting to changes in radio button on the client side of a Razor ASP.NET Core Page

I am trying to make a radio button on an ASP.NET Core Razor page control the appearance of another UI element without requiring a roundtrip to the server.

Here is an example of what I am trying to do, but with a roundtrip to server.

Running program looks like this:

运行程序

Here is the relevant code:

// Test.cshtml
<h3 style="color:@Model.Color">Hello in @Model.Color</h3>

<form method="post">
    <input type="radio" asp-for="Color" value="red" />Red<br />
    <input type="radio" asp-for="Color" value="green" />Green<br />
    <input type="radio" asp-for="Color" value="blue" />Blue<br />
    <input type="submit"/>
</form>

// Test.cshtml.cs
public class TestModel : PageModel {
    [BindProperty]
    public string Color { get; set; }
    public async Task<IActionResult> OnGetAsync() {
        return Page();
    }
}

In order for the text to change color, end-users must click [Submit]; I would like to avoid it. Please suggest a client-side solution.

Since this will be done client-side, you can use javascript.

document.querySelector and document.querySelectorAll are used to select elements from the DOM and operate using CSS style selectors. Select the radio buttons and add an onclick event to each. In the onclick event update the h3 style and text.

The below snippet uses plain javascript. jQuery is another great tool I'd recommend for this kind of task.

 var radios = document.querySelectorAll('input[type=radio]'); for (radio in radios) { radios[radio].onclick = function() { var h3 = document.querySelector('h3'); h3.style.color = this.value; h3.innerText = 'Hello in ' + this.value; } }
 <h3 style="color:@Model.Color">Hello in @Model.Color</h3> <input type="radio" asp-for="Color" value="red" />Red<br /> <input type="radio" asp-for="Color" value="green" />Green<br /> <input type="radio" asp-for="Color" value="blue" />Blue<br />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM