简体   繁体   English

在ASP.NET MVC2中绑定ISet

[英]Bind ISet in ASP.NET MVC2

I am trying to find out what would be the best way to bind first element of ISet ( Iesi.Collection ) as a first element. 我试图找出什么是对的第一个元素结合的最佳方式ISetIesi.Collection )作为第一要素。

So basically I only have to use some kind of collection that has an indexer (and ISet doesn't) then I can write code like this (which works perfectly well): 因此,基本上,我只需要使用具有索引器的某种集合(而ISet则没有),那么我就可以编写这样的代码(效果很好):

<%: Html.EditorFor(x => x.Company.PrimaryUsers[0].Email) %>

But as the ISet has no indexer I cannot use it. 但是由于ISet没有索引器,因此无法使用它。

So how can I then bind the first element of ISet in MVC2? 那么如何在MVC2中绑定ISet的第一个元素呢?

Thanks, 谢谢,
Dmitriy. 德米特里

Unfortunately those strongly typed helpers work only with indexer properties for collections. 不幸的是,那些强类型的助手仅与集合的索引器属性一起使用。 They would actually look for opening and closing [ ] brackets in the syntax. 他们实际上会在语法中寻找打开和关闭[ ]括号。

A possible workaround would be to add another property in your view model class which would be of type IList and would be populated from the original property. 可能的解决方法是在视图模型类中添加另一个属性,该属性的类型为IList并从原始属性填充。 In the getter you would simply return a new list from the original property and in the setter you would reconstruct the original set as it does not have the notion of order. 在getter中,您只需从原始属性返回一个新列表,而在setter中,您将重建原始集,因为它没有顺序的概念。

You can pull this off via the following: 您可以通过以下方法实现:

<%
  int i = 0;
  foreach (var element in Model.Company.PrimaryUsers) {
    string htmlFieldName = String.Format("Company.PrimaryUsers[{0}]", i);
    %><%: Html.EditorFor(_ => element, null /* templateName */, htmlFieldName) %><%
    i++;
  }
%>

This particular overload of EditorFor() says "I'm going to pass you a model, but use the htmlFieldName string for the model rather than trying to deduce it from the expression." EditorFor()的这种特殊重载说:“我将向您传递一个模型,但为模型使用htmlFieldName字符串,而不是尝试从表达式中推导它。” You have to keep track of the i manually in this case. 在这种情况下,您必须手动跟踪i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM