【问题标题】:Using HTML.TextBoxFor to loop through items in a model [duplicate]使用 HTML.TextBoxFor 循环遍历模型中的项目 [重复]
【发布时间】:2016-07-05 14:16:56
【问题描述】:

可能是一个愚蠢的问题,但我是 MVC 新手。

到目前为止,在我的 Razor 中,我可以说 @HTML.TextBoxFor(t => t.EmailAddress) 但现在我有一个 for-each:

foreach(var q in Model.Questions)
{
  // so here the t => t.EmailAddress  syntax is not working anymore.
}

我在上面的代码示例中提出了我的问题。因此,当我在 for-each 循环中时,如何使用 @HTML.TextBox ?因为现在它不再获得 lambda 语法了。

【问题讨论】:

标签: c# asp.net-mvc razor


【解决方案1】:

不要使用foreach,因为这会在您尝试将输入绑定回模型时导致问题。而是使用for 循环:

for (var i = 0; i < Model.Questions.Count(); i++) {
    @Html.TextBoxFor(m => m.Questions[i])
}

另见Model Binding to a List MVC 4

【讨论】:

  • 如何将两个文本框绑定到两个不同的属性。
【解决方案2】:

您必须使用for 循环来完成此操作,因为您需要将元素的实际索引绑定到name 属性,该属性用于确保您的值正确发布到服务器:

@for (var q = 0; i < Model.Questions.Count(); q++) { 
    // This will bind the proper index to the appropriate name attribute
    @Html.TextBoxFor(x => x.Questions[q])
}

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 1970-01-01
    • 2012-09-15
    • 2020-06-22
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 2018-10-15
    • 2017-12-20
    相关资源
    最近更新 更多