用剃刀绑定ASP.NET MVC页面中的单选按钮 [英] Binding radio buttons in ASP.NET MVC page with razor

查看:80
本文介绍了用剃刀绑定ASP.NET MVC页面中的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有4个单选按钮(考试题和4个选项供您选择).使用下面的代码,我可以在用户单击按钮后读取选项值.

I have a page with 4 radio buttons (Exam question and 4 options to choose from). With the code below, I can read the option values after user clicks the button.

我有两个问题:

  • 为什么页面首次加载时所有单选按钮都被选中?
  • 如何找出发布后选择了哪个单选按钮?

谢谢!

StudentQuestions.cshtml

StudentQuestions.cshtml

@page "{examId:int?}"
@model VerityLearn.WebUI.Pages.Questions.StudentQuestionsModel
@{
    ViewData["Title"] = "StudentQuestions";
}
    <div>
        <form method="post">
            @Html.LabelFor(model => model.QuestionViewModel.QuestionText);

                <p>Select the correct option.</p>

                int optionIndex = -1;

                @foreach (OptionViewModel opt in Model.QuestionViewModel.Options)
                {
                    optionIndex++;

                    @Html.RadioButtonFor(model => model.QuestionViewModel.Options[optionIndex], Model.QuestionViewModel.Options[optionIndex]);
                    @opt.OptionText<br />
                }

            <button type="submit" asp-route-questionIndex="@(Model.QuestionNdx + 1)" class="btn btn-primary @nextDisabled">Next</button>

        </form>
    </div>

StudentQuestions.cshtml.cs

StudentQuestions.cshtml.cs

   public class StudentQuestionsModel : PageModel
    {
        //private readonly VerityContext _context;
        private readonly SignInManager<VerityUser> _signInManager;
        private readonly UserManager<VerityUser> _userManager;
        private readonly IStudentQuesionsUOW _studentQuesionsUOW;
        private readonly VerityLearn.DataAccess.VerityContext _context;

        public StudentQuestionsModel(
            VerityContext context,
            SignInManager<VerityUser> signInManager,
            UserManager<VerityUser> userMrg,
            IStudentQuesionsUOW studentQuesionsUOW
        )
        {
            _context = context;
            _signInManager = signInManager;
            _userManager = userMrg;
            _studentQuesionsUOW = studentQuesionsUOW;
        } // end public StudentQuestionsModel(VerityContext context, SignInManager<VerityUser> signInManager, UserManager<VerityUser> userMrg)

        [BindProperty]
        public QuestionViewModel QuestionViewModel { get; set; }

        [BindProperty]
        public Question Question { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            ... Not sure what to do here ...
        }

QuestionViewModel.cs

QuestionViewModel.cs

    public class QuestionViewModel
    {
        public int QuestionId { get; set; }

        public int ExamQuestionOrder { get; set; }

        public string QuestionText { get; set; }

        public bool? IsSingleSelection { get; set; }

        public List<OptionViewModel> Options { get; set; }
    } 

推荐答案

您感兴趣的是所选单选按钮的值.在我的演示中,为了简化起见,我假设它是一个id.假设单选按钮的名称为 AnswerSelectedId ,然后在提交表单时将标有 AnswerSelectedId 的值发布回服务器.因此,您需要在模型中定义一个名为 AnswerSelectedId 的属性,以便模型绑定可以将两者匹配.

The thing you are interested in is the value for the radio button that is selected. In my demo to make things simpler I've assumed it's an id. Suppose the radio buttons have name AnswerSelectedId, then a value labelled with AnswerSelectedId is posted back to the server when the form is submitted. Therefore you need to define a property in your model called AnswerSelectedId so that the model binding can match the two.

这是一个快速演示,向您展示您想从Mike Brind的答案中大量借鉴的经验.

Here is a quick demo to show what you are trying to achieve borrowing heavily from Mike Brind's answer.

StudentQuestions.cshtml.cs

StudentQuestions.cshtml.cs

public class OptionViewModel
{
    public int Id { get; set; }
    public string OptionText { get; set; }
}

public class QuestionViewModel
{
    public int QuestionId { get; set; }
    public int ExamQuestionOrder { get; set; }
    public string QuestionText { get; set; }
    public bool? IsSingleSelection { get; set; }
    public List<OptionViewModel> Options { get; set; }
}

public class StudentQuestionsModelModel : PageModel
{
    public void OnGet()
    {
        QuestionViewModel = new QuestionViewModel
        {
            QuestionId = 1,
            ExamQuestionOrder = 1,
            QuestionText = "Question1",
            IsSingleSelection = false,
            Options = new List<OptionViewModel>()
            {
                new OptionViewModel
                {
                    Id = 1,
                    OptionText = "Option 1"
                },
                new OptionViewModel
                {
                    Id = 2,
                    OptionText = "Option 2"
                }
            }
        };
    }

    [BindProperty]
    public QuestionViewModel QuestionViewModel { get; set; }

    [BindProperty]
    public int AnswerSelectedId { get; set; }   //this is the key bit

    public async Task<IActionResult> OnPostAsync()
    {
        return Content($"The answer selected was {AnswerSelectedId}");
    }
}

StudentQuestions.cshtml

StudentQuestions.cshtml

@page "{examId:int?}"
@model StudentQuestions.Pages.StudentQuestionsModel  

<div>
    <form method="post">
        @Html.LabelFor(model => model.QuestionViewModel.QuestionText);

        <p>Select the correct option.</p>    

        @for (var i = 0; i < Model.QuestionViewModel.Options.Count(); i++)
        {
            <input type="radio" asp-for="AnswerSelectedId" 
                   value="@Model.QuestionViewModel.Options[i].Id" /> 
                  @Model.QuestionViewModel.Options[i].OptionText
                  <br>
        }

        <button type="submit" class="btn btn-primary">Next</button>
    </form>
</div>

请注意asp-for属性如何与页面模型中的属性AnswerSelectedId匹配.

Note how the asp-for attribute matches the property AnswerSelectedId in your page model.

当您按下提交按钮时,表单数据将被发送到服务器.如果您在发送到服务器的表单数据下使用开发人员工具,它将看起来像这样(取决于所选的值)

When you submit is pressed form data will be sent to the server. If you use the developer tools under form data sent to the server it will look like this (depending on the value selected)

AnswerSelectedId: 1

然后,模型绑定会将值绑定到名为AnswerSelectedId的属性,然后您就可以通过onPostAsync方法访问它.

Then the model binding will bind the value to your property called AnswerSelectedId and you will then be able to access it in your onPostAsync method.

这篇关于用剃刀绑定ASP.NET MVC页面中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆