You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web应用单选按钮交互功能实现咨询

Hey there! Since you're new to ASP.NET Core and trying to build that quiz-style section where users select radio buttons, then see correct answers highlighted green and wrong ones red on submit, let me share two solid approaches—one frontend-focused for quick interactions, and one backend-driven for more secure/scalable scenarios. Both are beginner-friendly and fit well with ASP.NET Core's patterns.


Frontend-First Approach (Quick & Simple)

This is great if your quiz data is static and you don't need to save user responses server-side. We'll use JavaScript to handle the click event, check answers directly in the browser, and apply styling.

Step 1: Render the Quiz in Razor

First, we'll loop through your questions/options and add data attributes to mark which options are correct:

@page
@model QuizModel

<h1>Simple Quiz</h1>

<div class="quiz-wrapper">
    @foreach (var question in Model.Questions)
    {
        <div class="question-block">
            <h3>@question.Title</h3>
            @foreach (var option in question.Options)
            {
                <div class="option">
                    <input type="radio" 
                           name="question-@question.Id" 
                           id="opt-@option.Id" 
                           data-correct="@(option.Id == question.CorrectOptionId)" />
                    <label for="opt-@option.Id">@option.Text</label>
                </div>
            }
        </div>
    }
    <button onclick="validateAnswers()" class="submit-btn">Submit Answers</button>
</div>

Step 2: Add CSS for Highlighting

.quiz-wrapper { max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
.question-block { margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #eee; }
.option { margin: 0.5rem 0; padding: 0.3rem; }
.correct { background-color: #d4edda; color: #155724; border-radius: 4px; }
.incorrect { background-color: #f8d7da; color: #721c24; border-radius: 4px; }
.submit-btn { padding: 0.5rem 1rem; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }

Step 3: JavaScript for OnClick Logic

function validateAnswers() {
    // Clear any existing highlights
    document.querySelectorAll('.option').forEach(opt => {
        opt.classList.remove('correct', 'incorrect');
    });

    // Check each selected option
    document.querySelectorAll('input[type="radio"]:checked').forEach(radio => {
        const optionDiv = radio.closest('.option');
        const isCorrect = radio.dataset.correct === 'True';

        if (isCorrect) {
            optionDiv.classList.add('correct');
        } else {
            optionDiv.classList.add('incorrect');
            // Highlight the correct option for this question
            const questionId = radio.name.split('-')[1];
            const correctRadio = document.querySelector(`input[name="question-${questionId}"][data-correct="True"]`);
            if (correctRadio) {
                correctRadio.closest('.option').classList.add('correct');
            }
        }
    });

    // Disable radio buttons to prevent re-selection
    document.querySelectorAll('input[type="radio"]').forEach(radio => radio.disabled = true);
}

Step 4: Backend Model (for Rendering Data)

In your QuizModel.cshtml.cs, add a simple model to hold quiz data:

public class QuizModel : PageModel
{
    public List<Question> Questions { get; set; }

    public void OnGet()
    {
        // Mock data - replace with your actual questions
        Questions = new List<Question>
        {
            new Question
            {
                Id = 1,
                Title = "Which framework are we using?",
                Options = new List<Option>
                {
                    new Option { Id = 1, Text = "ASP.NET Core" },
                    new Option { Id = 2, Text = "PHP" },
                    new Option { Id = 3, Text = "Ruby on Rails" }
                },
                CorrectOptionId = 1
            }
        };
    }
}

public class Question
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<Option> Options { get; set; }
    public int CorrectOptionId { get; set; }
}

public class Option
{
    public int Id { get; set; }
    public string Text { get; set; }
}

Backend-Driven Approach (Secure & Scalable)

Use this if you need to save user responses, validate answers server-side (to avoid exposing correct answers in frontend code), or pull quiz data from a database. We'll use ASP.NET Core's form submission and model binding.

Step 1: Update the Page Model

Add a handler for form submission and track user-selected answers:

public class QuizModel : PageModel
{
    public List<Question> Questions { get; set; }

    // This will bind to the form's selected options
    [BindProperty]
    public List<int?> SelectedOptions { get; set; }

    public void OnGet()
    {
        Questions = GetQuizQuestions();
    }

    public IActionResult OnPost()
    {
        Questions = GetQuizQuestions();
        
        // Match user selections to questions
        for (int i = 0; i < Questions.Count; i++)
        {
            if (i < SelectedOptions.Count)
            {
                Questions[i].UserSelectedId = SelectedOptions[i];
            }
        }

        return Page();
    }

    private List<Question> GetQuizQuestions()
    {
        return new List<Question>
        {
            new Question
            {
                Id = 1,
                Title = "Which is a .NET language?",
                Options = new List<Option>
                {
                    new Option { Id = 1, Text = "C#" },
                    new Option { Id = 2, Text = "Python" },
                    new Option { Id = 3, Text = "Java" }
                },
                CorrectOptionId = 1
            }
        };
    }
}

// Update the Question class to track user selection
public class Question
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<Option> Options { get; set; }
    public int CorrectOptionId { get; set; }
    public int? UserSelectedId { get; set; }
}

Step 2: Render the Form in Razor

We'll use Razor to conditionally apply styles based on the server's validation:

@page
@model QuizModel

<h1>Secure Quiz</h1>

<form method="post">
    @foreach (var question in Model.Questions)
    {
        <div class="question-block">
            <h3>@question.Title</h3>
            @foreach (var option in question.Options)
            {
                <div class="option @GetOptionClass(question, option.Id)">
                    <input type="radio" 
                           name="SelectedOptions[@question.Id]" 
                           id="opt-@option.Id" 
                           value="@option.Id"
                           @(question.UserSelectedId == option.Id ? "checked" : "")
                           disabled="@(question.UserSelectedId.HasValue)" />
                    <label for="opt-@option.Id">@option.Text</label>
                </div>
            }
        </div>
    }
    @if (!Model.Questions.Any(q => q.UserSelectedId.HasValue))
    {
        <button type="submit" class="submit-btn">Submit Answers</button>
    }
</form>

@functions {
    private string GetOptionClass(Question question, int optionId)
    {
        if (!question.UserSelectedId.HasValue) return "";
        
        if (optionId == question.CorrectOptionId)
        {
            return "correct";
        }
        else if (optionId == question.UserSelectedId.Value)
        {
            return "incorrect";
        }
        return "";
    }
}

<!-- Use the same CSS as the frontend approach -->
<style>
.quiz-wrapper { max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
.question-block { margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #eee; }
.option { margin: 0.5rem 0; padding: 0.3rem; }
.correct { background-color: #d4edda; color: #155724; border-radius: 4px; }
.incorrect { background-color: #f8d7da; color: #721c24; border-radius: 4px; }
.submit-btn { padding: 0.5rem 1rem; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>

Which One to Choose?

  • Frontend Approach: Perfect for quick, static quizzes where you don't need to save responses. It's easy to set up and gives instant feedback.
  • Backend Approach: Better for dynamic quizzes (pulled from a database), when you need to store user answers, or when you don't want correct answers visible in frontend code. It follows ASP.NET Core's best practices for form handling and validation.

Since you're new to ASP.NET Core, I'd start with the frontend approach to get comfortable with Razor syntax and JavaScript interactions, then move to the backend approach once you're familiar with form submissions and model binding.

内容的提问来源于stack exchange,提问作者saas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:32:56