MVC WebGrid - 如何在 WebGridRow 项/模型上调用方法
本文关键字:模型 调用 方法 WebGridRow WebGrid MVC | 更新日期: 2023-09-27 17:56:37
时,我发现我可以访问绑定到 WebGrid 的模型上的属性,但我无法访问模型本身的方法。
例如,这有效:
// Accessing a property of item works
reportGrid.Column("", header: "First Name", format: item => item.firstName )
但这不起作用:(我展示了一个微不足道的示例,但对于我的情况,我必须在 User 对象本身上调用一个方法。
// 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%27t-Use-Extension-Methods-With-A-WebGrid
我看不到将这些解决方案应用于我的问题的方法。正如迈克·布林德所说:
WebGridColumn 的 Format 参数采用的参数是 代表:富克。这意味着你必须 传入动态类型,然后在它之前对其进行一些操作 作为对象返回。
。
当您尝试使用扩展方法时,编译器将检查 键入您尝试使用它以查看是否存在此类方法。如果它 不。它将检查类型派生自 to 的任何基类 查看它们是否包含具有正确名称的形式化方法。
似乎应该找到我的方法,但也许不是,因为绑定到 WebGrid 的模型实际上是一个分页模型,其中包含保存我的用户引用IList<T> LineItems
。
有没有办法强制转换或获取对 User 对象本身的引用,以便除了访问其属性之外还可以调用在其上定义的方法?
我找到了解决这个问题的方法,但我仍然希望有更好的方法。我将不胜感激对此解决方案或替代解决方案的任何反馈。
在探索这个问题并检查我的其他一些 WebGrid 代码时,我发现我能够访问针对对象定义的二阶方法,这些方法可以通过绑定到 WebGrid 的模型对象的属性进行访问。
示例(简化):
reportGrid.Column("", header: "First Name Backwards",
format: item => item.BestFriend.firstNameBackwards() )
=> Works!
更进一步,我将双向关系追溯到原始对象,以便我可以调用它的方法:
// Assume all best-friend relationships are reciprocal
reportGrid.Column("", header: "First Name Backwards",
format: item => item.BestFriend.BestFriend.firstNameBackwards() )
=> Works!
考虑到这一点,我修改了我的用户模型以包含对自身的引用:
public User() {
this._self = this; // Initialize User object with a reference to itself
}
[NotMapped]
public User _self { get; set; }
解决方案 - 现在我可以使用 _self 属性调用针对用户模型定义的方法。
reportGrid.Column("", header: "",
format: item => Helper.userTML(item._self.firstNameBackwards() ) )
=> Works!
我在探索这个问题并检查我的其他一些 WebGrid 代码时,我发现我能够访问针对对象定义的二阶方法,这些方法可以通过绑定到 WebGrid 的模型对象的属性进行访问。
有同样的问题,根据这条评论,我发现这是因为我没有公开模型的数据成员。将 firstName 定义设置为公共,这将修复它。
我发现对我有用的最好方法是在模型类中使用getter。
在您的模型类(用户?
public string firstNameBackwards
{
get
{
var firstNameBackwards = firstName;
// Do something here
return firstNameBackwards;
}
}
在网络网格中:
reportGrid.Column("", header: "First Name Backwards", format: item => item.firstNameBackwards )