1

我正在尝试使用Html.NameFor<>方法生成元素名称,这是我的代码:

@foreach (var category in Model.Categories)
{
  <input type="hidden" name="@Html.NameFor(m=> category.CategoryId)" 
    value="@category.CategoryId" />
}

生成的项目name得到这个值:category.CategoryId,而不是Categories[i].CategoryId(这里i指的是当前索引器)。

为什么它不起作用?

4

3 回答 3

3

简而言之,使用 for 循环而不是 foreach 循环(请参阅此处的答案)。您需要手动索引它

MVC Razor 视图嵌套 foreach 的模型

编辑:添加示例代码

@for(int i=0; i < Model.ListTwo.Count; i++) 
{
    @Html.HiddenFor(t => t.ListTwo[i].Id)
}

好的,对于从 ICollection 继承的集合,请尝试

@for (int i = 0; i < Model.CollectionThree.Count; i++) 
{
   @Html.Hidden("CollectionThree[" + i + "].Id", Model.CollectionThree.ElementAt(i).Id)
}

另一个编辑:为避免使用属性名称,您可以执行类似的操作

@for (int i = 0; i < Model.CollectionThree.Count; i++)
{
   @Html.Hidden(Html.NameFor(t => Model.CollectionThree) + "[" + i + "]." +
                Html.NameFor(t =>Model.CollectionThree.ElementAt(i).Id)
               ,Model.CollectionThree.ElementAt(i).Id )
}

它不优雅,但它没有硬编码属性名称。

然后让这些人脱离循环

 @{
   var collectionname = Html.NameFor(t => Model.CollectionThree);
   var propname = Html.NameFor(t => Model.CollectionThree.First().Id);
  }

@for (int i = 0; i < Model.CollectionThree.Count; i++)
 {
      @Html.Hidden( collectionname+ "[" + i + "]." + propname ,Model.CollectionThree.ElementAt(i).Id )
 }

我很抱歉没有早点回复。我退出了,因为我还有其他事情要做。您可能还想进行空检查,即,如果 count > 0,则分配 propname,否则跳过整个事情

于 2013-06-08T23:34:41.013 回答
1

根据user1778606 的回答,我将使用该道具。名称和索引器分开,像这样:

@{
 var modelName = Html.NameFor(m => m.Categories);
 var catIndex = 0;   
}

@foreach (var category in Model.Categories)
{ 
 <input type="hidden" class="checkbox"
   name="@string.Format("{0}[{1}]", modelName, catIndex++)"
   value="@category.CategoryId" />      
}
于 2013-06-09T00:00:12.880 回答
0

使用@Html.HiddenFor并传入数组索引表达式CategoryId

@for(int i=0; i < Model.Categories.Count; i++)
{
    @Html.HiddenFor(m => Model.Categories[i].CategoryId)
}
于 2016-11-18T17:05:09.297 回答