SelectList 扩展 - 情侣表达式
所以我有了一个疯狂的想法,我可以让一些很酷的东西发挥作用。我厌倦了 new selectlist(item, "blah", "blahblah") 所以我开始编写一个扩展方法(试图让它更强类型化)像这样......
var selectList = projects.ToSelectList(p =>p.ProjectID, p =>p.ProjectName);
扩展方法有点像这样
public static SelectList ToSelectList<T>(this IEnumerable<T> item,
Expression<Func<T, string>> textName,
Expression<Func<T, string>> valueProperty)
{
//do cool stuff
return new SelectList(items, dataTextField, dataValueField);
}
我需要什么获取的是反射属性,这样我就可以获取值并获取名称。关于我如何做到这一点有什么想法吗?有什么想法可以做得更好/更容易吗?我以前曾经这样做过,但我一辈子都不记得我是怎么做到的。
编辑这需要一些澄清。我复制了一些正在运行且未完善的代码,因此我更新了该代码以反映更正确的标准。
So I got this crazy idea I could make make something cool work. I got tired of new selectlist(item, "blah", "blahblah") so I started writing an extension method (trying to get it more strongly typed) something like this ...
var selectList = projects.ToSelectList(p =>p.ProjectID, p =>p.ProjectName);
the extension method goes a little like this
public static SelectList ToSelectList<T>(this IEnumerable<T> item,
Expression<Func<T, string>> textName,
Expression<Func<T, string>> valueProperty)
{
//do cool stuff
return new SelectList(items, dataTextField, dataValueField);
}
What I need to get to is the reflection properties so I can grab the value and grab the name. Any ideas onhow I can do that? Any thoughts on doing this more better/easier? I've done this before but for the life of me I can't remember how I did it.
Edit this needed some clarification. I copied some code that was in-flight and not refined, so I've updated that code to reflect the more correct criteria.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不明白为什么你必须使用反射来做到这一点。
应该可以,但我当前机器上没有 MVC dll。
I don't see why you have to use Reflection to do this.
should would work, but I don't have the MVC dll on the current machine.
当我开始使用 MVC 时,我最初也尝试过你的想法,但后来我意识到我想以某种方式格式化某些字段,以及默认情况下应该选择某个项目时该怎么办。处理完所有这些之后,我意识到只编写一行 LAMDA 表达式会更清晰。
所以现在我通常只做一个 LAMDA 表达式来生成我的 SelectListItem 集合。
看起来这就像你的想法一样清楚正在发生的事情。
另一个例子
I originally tried your idea as well when I started with MVC but then I realized that some fields I wanted to format in a certain way and what about when an item is supposed to be selected by default. After handling all of that I realized it would be clearer to just write a one line LAMDA expression.
So now I usually just do a LAMDA expression to generate my SelectListItem collection.
It seems like this is just as clear as to what is going on as what your idea is.
Another Example
这需要清理和测试诸如物品零计数之类的事情,但这是最终结果。
This needs cleaned and tested for things like a zero count of the items, but here's the end result.