元素的foreach循环内剃刀发电机命名规则 [英] Element naming convention in Razor generator within a foreach loop

查看:74
本文介绍了元素的foreach循环内剃刀发电机命名规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用生成元素名称 Html.NameFor<> 的方法,这是我的code:

I'm trying to generate element names using Html.NameFor<> method, here's my code:

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

生成项目的名称得到这个值: category.CategoryId ,而不是分类[I] .CategoryId (其中 I 指当前索引)。

The generated item's name get this value: category.CategoryId, instead of Categories[i].CategoryId (where i refers to the current indexer).

为什么不工作?

推荐答案

,使用for循环而不是foreach循环(看到这里的答案)。您需要手动指数为

in short, use a for loop instead of a foreach loop (see the answer here). You need to manually index it

MVC的Razor视图嵌套的foreach模型

编辑:添加样品code

added sample code

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

好吧,对于自ICollection继承收藏,尽量

Okay, for collections that inherit from ICollection, try

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

另一个编辑:
为了避免使用属性的名称,你可以不喜欢

Another edit: To avoid using the property name, you could do something like

@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 )
}

其不雅,但它并不难code中的属性名称。

Its inelegant, but it doesn't hardcode the property name.

然后让我们这些家伙圈外

And then lets take those guys out of the loop

 @{
   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 )
 }

我的道歉早期没有响应。我注销了,因为我有别的事情要做。你也可以做一个空检查也就是说,如果计数> 0,则分配PROPNAME,否则跳过整个事情

My apologies for not responding earlier. I logged out as I had other things to do. You also may want to do a null check ie, if count > 0, then assign the propname, otherwise skip the whole thing

这篇关于元素的foreach循环内剃刀发电机命名规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆