1

假设我有下面的视图模型。

public class CustomerListViewModel {
  public IEnumerable<CustomerViewModel> Customers { get; set; }
}

public class CustomerViewModel {
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Email { get; set; }
  public int Age { get; set; }
}

我想在 for-each 循环内的视图中显示客户列表。我还想使用 DisplayFor 来显示应用了约定的值(而不是仅按原样输出属性:customer.Age)。使用 ASP.NET MVC,我过去常常忽略表达式中的 lambda 变量(正如这个问题的提问者所发现的那样)。

<% foreach (var customer in Model.Customers) { %>
  ...
  <li><%: this.DisplayFor(m => customer.Age) %></li>
<% } %>

但是,如果我这样做,我会收到 FubuMVC 错误。

无法将“System.Reflection.RtFieldInfo”类型的对象转换为“System.Reflection.PropertyInfo”类型。

我必须使用局部来适当地使用 DisplayFor 呈现每个客户吗?

提前致谢!

4

1 回答 1

4

在 display 的这种特殊用途中:

<%: this.DisplayFor(m => customer.Age) %>

重载正在寻找引用 m 成员的表达式。这里使用“客户”是导致反射异常的原因。

这里还有一个额外的重载:https ://github.com/DarthFubuMVC/fubumvc/blob/master/src/FubuMVC.Core/UI/FubuPageExtensions.cs#L229

这允许您显式指定模型类型和实例:

<%: this.DisplayFor<Customer>(customer, c => c.Age) %>
于 2012-03-29T02:38:54.377 回答