开发者

MVC IEnumerable of EditorFor Template; how to get the count

开发者 https://www.devze.com 2023-02-25 14:42 出处:网络
ViewModel: public class Foo { IEnumerable<Bar> Bars { get; set; } Foo Template: @Html.EditorFor(x => x.Bars)

ViewModel:

public class Foo {
    IEnumerable<Bar> Bars { get; set; }

Foo Template:

@Html.EditorFor(x => x.Bars)

Bar Templ开发者_C百科ate:

//this is the closest I could find 
@ViewData.TemplateInfo.HtmlFieldPrefix //equals "Bars[0]" on the first iteration

Is there a way to get the count of the current iteration inside the template during the render process? Aside from parsing the HtmlFieldPrefix string into a count.


Could you restructure your view so that it did something like this:

@for( int idx = 0; idx < Model.Count; idx++ )
{
    @Html.EditorFor(m=>m[idx])
}

Apologies if IEnumerable<> doesn't support Count, but if it doesn't you could use some other collection which does.


Just to share here since this question useful to me and UIHint and template help me too.

I stick not to touch the Foo template but count should be displayed in the Bar template. so this is how EditorFor handle IEnumerable.

  1. I will use ICollection because EF does not support IEnumerable for lazy loading. ICollection has Count property.
  2. Even if I need to use IEnumerable. I will iterate through the collection and do i++. Later, after the iteration or foreach finished, i is the total.
0

精彩评论

暂无评论...
验证码 换一张
取 消