【问题标题】:Model binder data issue from a EditorTemplate来自 EditorTemplate 的模型绑定器数据问题
【发布时间】:2023-03-19 03:21:01
【问题描述】:

我在 Razor 视图的列表中显示。在其中,我有几个显示在列表视图中的编辑器模板。这是我的编辑器模板。

@using Contoso.MvcApplication.Extensions
@model Contoso.MvcApplication.ViewModels.MultipleChoiceQuestionViewModel

<h5>@Model.Question.QuestionText</h5>

<div>
@Html.RadioButtonForSelectList(m => m.Question.SelectedAnswer, Model.AnswerRadioList)
@Html.ValidationMessageFor(m => m.Question.SelectedAnswer)
</div>

问题是我在哪里设置了RadioButtonForSelectList,它的绑定是如此,因为我知道在这种情况下应该在这样的for循环中:

@Html.RadioButtonForSelectList(m => m[i].Question.SelectedAnswer, Model.AnswerRadioList) // the index

但是从编辑器模板中,我无法知道 lambda 表达式中的索引。

这是我从中复制 html 扩展名的站点:

http://jonlanceley.blogspot.mx/2011/06/mvc3-radiobuttonlist-helper.html

这是我正在使用的视图模型

public class MultipleChoiceQuestionViewModel
{
    public MultipleChoiceQuestion Question { get; set; }
    public List<SelectListItem> AnswerRadioList { get; set; }
}

如何正确绑定radioButton?

当我阅读代码中的标签时,我列表中的所有模型都有相同的 id:Question.SelectedAnswer。我认为这是错误的,因为应该有一个像这样的索引 ID:Question.SelectedAnswer.[INDEX]

更新:

    public ActionResult Index(short testId)
    {
        GenerateQuiz(testId);
        StartQuiz();

        return View(CreateQuestionViewModel((MultipleChoiceQuestion)CurrentQuestion));
    }

    [HttpPost]
    public ActionResult Index(MultipleChoiceQuestionViewModel q)
    {
        // Save answer state
        ((MultipleChoiceQuestion)CurrentQuestion).SelectedAnswer = q.Question.SelectedAnswer;

        if (CurrentNumber == Questions.Count - 1)
        {
            QuizCompleted();
            return RedirectToAction("ShowResults");
        }
        else
        {
            NextQuestion();
            return View(CreateQuestionViewModel((MultipleChoiceQuestion)CurrentQuestion));
        }
    }

【问题讨论】:

  • 那么,您有多个问题并想添加一个 foreach 以在视图中显示它们?不知道我是否理解,请您澄清一下吗?
  • 最后一个 razor 视图是 EditorTemplate。是的,我有多个问题,我正在通过我的控制器一一显示..让我更好地向您展示代码

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 model-binding


【解决方案1】:

显示问题的视图部分应如下所示:

@for (int j = 0; j < Model.Questions.Count; j++)
{
    <h5>
         Model.Questions[j].QuestionText
    </h5>
    <div>
       @Html.RadioButtonForSelectList(m => m.Questions[j].SelectedAnswer, Model.AnswerRadioList)
    </div>
}

【讨论】:

  • 我也是这样,但我不能这样做,因为问题可能有多个模板(FreeResponse、MultipleChoice 等)。这就是我使用 EditorTemplates 的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多