MVC Razor视图在for循环内部失去了Variable作用域
本文关键字:失去 Variable 作用域 内部 循环 Razor 视图 for MVC | 更新日期: 2023-09-27 18:27:50
我有一个剃刀视图,一旦进入forloop,它就会丢失变量范围。在我添加表标记之前,它工作得很好。因此,我对ViewModel的不同部分的所有调用都不再有效。请告诉我,如果还有什么可以帮助我知道的。
@model Auditor_Evaluations_MVC.ViewModels.EvaluationViewModel
@using (Html.BeginForm())
{
<div>
<table class="table table-condensed" style="width:825px;">
for(int i = 0; i < Model.QuestionGroup.Count; i++)
{
var questionGroup = Model.QuestionGroup[i];
@Html.HiddenFor(m => Model.QuestionGroup[i].GroupName)
@Html.HiddenFor(m => Model.QuestionGroup[i].GroupId)
<thead>
<tr>
<th class="text-left">@Html.Label(questionGroup.GroupName) </th>
<th class="text-center">Excellent</th>
<th class="text-center">Good</th>
<th class="text-center">Fair</th>
<th class="text-center">Poor</th>
<th class="text-center">N/A</th>
</tr>
</thead>
var questions = questionGroup.Questions;
for(int j = 0; j < questions.Count; j++)
{
@Html.HiddenFor(m => Model.QuestionGroup[i].Questions[j].QuestionName)
<tr>
<td class="text-left">@Html.Label(questions[j].QuestionName) </td>
var questionResponse = questions[j].QuestionResponses;
@for(int k = 0; k < questionResponse.Count; k++)
{
<td class="text-center" style="width:75px">
@Html.RadioButtonFor(m => Model.QuestionGroup[i].Questions[j].SelectedAnswer,questionResponse[k].QuestionValue)
</td>
}
</tr>
}
}
<tr>
<td colspan="6"> </td>
</tr>
<tr>
<td colspan="6"><strong>@Model.GeneralQuestion1Text</strong></td>
</tr>
<tr>
<td colspan="6">@Html.TextAreaFor(m => m.GeneralQuestion1Value)</td>
</tr>
<tr>
<td colspan="6"><strong>2. Additional Comments:</strong></td>
</tr>
<tr>
<td colspan="6">@Html.TextAreaFor(m => m.GeneralQuestion2Value)</td>
</tr>
<tr>
<td colspan="6"><strong>3. Would you like the appropriate audit manager to contact you regarding any or all of the information relayed through this questionnaire? If yes, please include your name and telephone number.</strong></td>
</tr>
<tr>
<td colspan="6">@Html.TextAreaFor(m => m.GeneralQuestion3Value)</td>
</tr>
<tr>
<td colspan="6"><input type="submit" value="Submit"/></td>
</tr>
</table>
</div>
}
我不能100%确定你的问题是什么,这个问题有点令人困惑,但所有你这样做的地方:
@Html.HiddenFor(m => Model.QuestionGroup[i].GroupName)
可能应更换为
@Html.HiddenFor(m => m.QuestionGroup[i].GroupName)
即使用m
变量在lambda表达式中表示您的模型,而不是引用Model
属性。
此外,在这条线上:
<table class="table table-condensed" style="width:825px;">
for(int i = 0; i < Model.QuestionGroup.Count; i++)
您需要在for
关键字前面添加一个@
。
尝试在Razor块中使用foreach
foreach(var question in Model.QuestionGroup) {
@Html.HiddenFor(m => m.question.GroupName)
@Html.HiddenFor(m => m.question.GroupId)
...
etc.
更新:如果您的模型在发送时没有映射到正确的ViewModel,您可能需要查看EditorFor和EditorForModel HTML帮助程序