[英]ASP.NET Core MVC post model with IEnumerable or List fields are null
我需要幫助來找出下一個錯誤。 我正在嘗試使用列表參數發布 model 。 但是,當我收到列表時,它有一個 null 值。
Model class:
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>
controller 獲取值,但集合作為 null 接收。
[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");
}
您只能使用表單發送輸入元素,也可以使用 javascript xhr 請求將它們作為參數發送。
關於 razor 最重要的是輸入元素 [名稱] 屬性需要匹配 model 字段。
<input type="text" name="questions[1].Id" class="form-label fw-bold" value="@Model.questions[1].Id" />
如果您處理嵌套對象,則它必須反映在您嘗試在服務器端綁定的 Model 上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.