关于 c#:MVC WebGrid – 如何在 WebGridRow 项目/模型上调用方法?

MVC WebGrid - How to call a method on WebGridRow item / model?

在使用 WebGrids 时,我发现我可以访问绑定到 WebGrid 的模型上的属性,但我无法访问模型本身上的方法。

举个例子,这行得通:

1
2
// Accessing a property of item works
reportGrid.Column("", header:"First Name", format: item => item.firstName )

但这不起作用:
(我展示了一个简单的例子,但就我而言,我必须在 User 对象本身上调用一个方法。)

1
2
3
4
// Accessing a method on item does not work
reportGrid.Column("", header:"First Name Backwards", format: item => item.firstNameBackwards() )

=> error: 'System.Web.Helpers.WebGridRow' does not contain a definition for 'getFullName'

这似乎与以下内容有关:

为什么我不能在 Razor WebGrid 的委托中使用我的扩展方法
http://www.mikesdotnetting.com/Article/171/Why-You-Can't-Use-Extension-Methods-With-A-WebGrid

我看不到将这些解决方案应用于我的问题的方法。正如 Mike Brind 所说:

The argument that the WebGridColumn's Format parameter takes is a
delegate: Func. What this means is that you have to
pass in a dynamic type, and then something is done to it before it is
returned as an object.

...

When you try to use an extension method, the Compiler will check the
type you are trying to use it on to see if such a method exists. If it
doesn't. it will check any base classes that the type derives from to
see if they contain a formal method with the right name.

似乎应该找到我的方法,但可能不是因为绑定到 WebGrid 的模型实际上是一个包含 IList<T> LineItems 的分页模型,其中包含我的用户引用。

有没有什么方法可以转换或获取对 User 对象本身的引用,以便我可以调用它定义的方法以及访问它的属性?


我找到了解决这个问题的方法,但我仍然希望有更好的方法。我将不胜感激有关此或替代解决方案的任何反馈。

在探索这个问题并检查我的其他一些 WebGrid 代码时,我发现我能够访问针对对象定义的二阶方法,这些对象可以通过绑定到 WebGrid 的模型对象上的属性来访问。

示例(简化):

1
2
3
reportGrid.Column("", header:"First Name Backwards",
  format: item => item.BestFriend.firstNameBackwards() )
=> Works!

更进一步,我将双向关系追溯到原始对象,因此我可以调用它的方法:

1
2
3
4
5
// Assume all best-friend relationships are reciprocal
reportGrid.Column("", header:"First Name Backwards",
  format: item => item.BestFriend.BestFriend.firstNameBackwards() )

=> Works!

考虑到这一点,我修改了我的用户模型以包含对自身的引用:

1
2
3
4
5
6
    public User() {
        this._self = this; // Initialize User object with a reference to itself
    }

    [NotMapped]
    public User _self { get; set; }

解决方案 - 现在我可以使用 _self 属性调用针对 User 模型定义的方法。

1
2
3
4
reportGrid.Column("", header:"",
  format: item => Helper.userTML(item._self.firstNameBackwards() ) )

=> Works!

我发现最适合我的方法是在模型类中使用 getter。

在您的模型类(用户?)中:

1
2
3
4
5
6
7
8
9
public string firstNameBackwards
{
    get
    {
        var firstNameBackwards = firstName;
        // Do something here
        return firstNameBackwards;
    }
}

在您的网络网格中:

1
reportGrid.Column("", header:"First Name Backwards", format: item => item.firstNameBackwards )

In exploring this issue and examining some of my other WebGrid code, I found that I am able to access 2nd order methods defined against objects that can be accessed through properties on the model object bound to the WebGrid.

我遇到了同样的问题,根据这条评论,我发现这是因为我没有公开模型的数据成员。将您的 firstName 定义设置为 public,这将解决它。