如何在ASP.Net Core 2和Razor中创建多个Radiobutton组?

时间:2018-05-21 19:29:27

标签: razor asp.net-core-2.0

我想创建多个分组的单选按钮。所以,基本上我有多个问题和3个带答案的单选按钮。我面临的问题是如何返回多个单选按钮的选定值。

控制器

public IActionResult Test()
    {
        SafetyObservationCardForm form = new SafetyObservationCardForm();
        using (IDbConnection dbConnection = Connection)
        {
            dbConnection.Open();
            var questions = dbConnection.Query<QuestionsViewModel>("SELECT * FROM SOCQuestions ORDER BY soc_order_id");

            var observationType = new List<ObservationType>
            {
                new ObservationType { Id = 1, Name = "Safe" },
                new ObservationType { Id = 2, Name = "At Risk" },
                new ObservationType { Id = 3, Name = "N/A" }
            };

            var rb = new List<Answer>();
            foreach (var item in questions)
            {
                rb.Add(new Answer { Id = item.soc_question_id, ObservationTypes = observationType }); 
            };

            form.Answers = rb;
            form.Questions = questions.ToList();

            return View(form);
        }
    }

模型

public class SafetyObservationCardForm
{
    public List<QuestionsViewModel> Questions { get; set; }
    public string Comments { get; set; }
    public string Location { get; set; }
    public string Observer { get; set; }
    public DateTime TimeStamp { get; set; }
    public string Task { get; set; }
    public ObserverType ObserverType { get; set; }
    public IEnumerable<Answer> Answers { get; set; }
}
public class ObserverType
{
    public bool Supervisor { get; set; }
    public bool Peer { get; set; }
    public bool Self { get; set; }
    public bool Other { get; set; }
}

public class ObservationType
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Answer
{
    public int Id { get; set; }
    public IEnumerable<ObservationType> ObservationTypes { get; set; }
    public int SelectedObservation { get; set; }
    }
}

查看

这里我正在尝试循环。当我因某种原因提交表单时,答案模型为空。

@model DBI.Safety.Models.SafetyObservationCardForm
<form asp-action="CreateTest">
@foreach (var answer in Model.Answers)
{
    <input name="@answer.Id" asp-for="@answer.SelectedObservation" type="radio" 
    value="@answer.Id" /> @answer.ObservationTypes
}
</form>

0 个答案:

没有答案