gpt4 book ai didi

c# - Asp.net MVC Razor如何显示两个模型字段的分组单选按钮

转载 作者:行者123 更新时间:2023-12-01 23:39:47 27 4
gpt4 key购买 nike

我有一个简单的测验模型,我试图让用户从强类型 View 中分组的两个单选按钮中选择正确答案/替代答案。但我使用的 lambda 表达式不起作用。我得到两个空白的单选按钮。我在这里和网上查看了几个问题,但我的模型是 IList<>,并且我找不到合适的示例。我发现的所有示例都适用于非 IList<>。

这是我的模型

型号:

public partial class Question
{
public int QuestionID { get; set; }
public string QuestionBody { get; set; }
public string CorrectAnswer { get; set; }
public string AlternativeAnswer { get; set; }
}

我的 Controller

public ActionResult Index()
{
QuizSimpleEntities quizEntities = new QuizSimpleEntities();
var questions = from p in quizEntities.Questions
select p;

return View(questions.ToList());

}

我的模型:

  @model IList<Quiz.Models.Question>                                

<h2>Welcome to the Quiz</h2>
@Html.BeginForm(method:FormMethod.Post,controllerName:"Home",actionName:"index")
{
@foreach (var questions in Model)
{

<p>@questions.QuestionBody</p>

@* How to display the CorrectAnswer and AlternativeAnswer
as two radio buttons grouped here? I will be posting the selected value back
}

}

谢谢

最佳答案

您的 View 模型上需要有一个属性,用于在发布表单时保存所选答案:

public partial class Question
{
public int QuestionID { get; set; }
public string QuestionBody { get; set; }
public string CorrectAnswer { get; set; }
public string AlternativeAnswer { get; set; }

public string SelectedAnswer { get; set; }
}

然后简单地循环模型的元素并生成所需的标记:

@model IList<Quiz.Models.Question>                                

<h2>Welcome to the Quiz</h2>
@Html.BeginForm( method:FormMethod.Post, controllerName:"Home", actionName:"index")
{
@for (var i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(x => x[i].QuestionID)
<fieldset>
<legend>
@Html.DisplayFor(x => x[i].QuestionBody)
</legend>
<ul>
<li>
@Html.HiddenFor(x => x[i].CorrectAnswer)
@Html.RadioButtonFor(x => x[i].SelectedAnswer, Model[i].CorrectAnswer)
@Html.DisplayFor(x => x[i].CorrectAnswer)
</li>
<li>
@Html.HiddenFor(x => x[i].AlternativeAnswer)
@Html.RadioButtonFor(x => x[i].SelectedAnswer, Model[i].AlternativeAnswer)
@Html.DisplayFor(x => x[i].AlternativeAnswer)
</li>
</ul>
</fieldset>
}

<button type="submit">OK</button>
}

注意:提交表单后,POST 操作可能会出现 IList<Question>您将在其中获得每个问题的答案的模型(在 SelectedAnswer 属性中)。

关于c# - Asp.net MVC Razor如何显示两个模型字段的分组单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17987360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com