【发布时间】:2021-02-27 21:27:16
【问题描述】:
我需要帮助来找出下一个错误。我正在尝试使用列表参数发布模型。但是,当我收到列表时,它的值为空。
模型类:
public class DiagModel{
public List<Component> components { get; set; }
public List<Question> questions { get; set; }
public List<Answer> answers { get; set; }
public List<Questionnaire> forms { get; set; } //it populates after instatiate object from the questions
//forms->(The propierties are idQuestion and idAnswer)
}
视图如下所示(省略了 fors 中对象的每个属性的@Html.hiddenFor()):
@using Test.Models.compounds;
@model DiagModel;
@{
Layout = "~/Views/Shared/_LayoutCommon.cshtml";
}
@if (!string.IsNullOrEmpty(ViewBag.Message))
{
<script type="text/javascript">
alert("@ViewBag.Message");
</script>
}
@using (Html.BeginForm(new { @id = "requestForm" }))
{
@for (int i = 0; i < Model.components.Count(); i++)
{
//The hidden components with razor helper was deleted to make short the code [Component]
<div class="row text-center">
<div class="col-md-10 offset-md-1 text-start" style="background-color: #dddddd">
<span class="text-start">@Model.components[i].name</span>
</div>
</div>
<div class="row"> </div>
List<Question> _questions = Model.questions.Where(p => p.Idcomponent == Model.components[i].Idcomponent).ToList();
for (int j = 0; j < _questions.Count; j++)
{
//The hidden components with razor helper was deleted to make short the code [Question]
<div class="row p-1">
<div class="col-md-10 offset-md-1 text-start">
<label class="form-label fw-bold">@_questions[j].Idquestion @_questions[j].Textopregunta</label>
@Html.DropDownListFor(model => model.forms.Where(c => c.Idquestion == @_questions[j].Idquestion).First().Idanswer, new SelectList(Model.answers.Where(r => r.Idquestion == @_questions.ElementAt(j).Idquestion), "Idquestion", "Text"), "Select an option", new { @class = "form-control" })
</div>
</div>
<div class="row"> </div>
}
}
<div class="row p-1 text-center">
<div class="col-md-12">
<button name="submit" type="submit" class="btn btn-danger" formaction="Question" value=@Model>Enviar</button>
</div><!--end col -->
</div>
}
<div class="row p-2"> </div>
控制器获取值但集合被接收为空。
[HttpPost]
public ActionResult Question(DiagModel model){
//ViewBag.Message($"Q #1: {model.forms.First().IdQuestion} , R #1: {model.forms.First().IdAnswer}");
ViewBag.Message = $"count: {model.forms.Count}";//Breakpoint
if (ModelState.IsValid) {
return View(model);
}
return View("Index");
}
【问题讨论】: