ASP.net MVC自定义字符串输出重载运算符<%=h
我目前正在制作一个新的 ASP.net MVC 网站,发现自己到处都在使用 Html.Encode,这是很好的做法,但变得非常混乱。 我认为清理这个问题的一个好方法是如果我可以重载一个运算符来自动进行 Html 编码。
以前:
<%= Html.Encode( ViewData['username'] ) %>
相当于:
<%=h ViewData['username'] %>
任何人都知道如何做到这一点,也许使用扩展方法或其他方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不像运算符重载那么干净,但我使用了以下扩展方法:
所以在我的 aspx id do:
将额外的方法添加到表达式的末尾对我来说看起来比通过函数发送值更漂亮。
It's not so clean as an operator overload, but I used the following extension method:
So in my aspx id do:
Tacking the extra method onto the end of the expression just looks prettier to me than sending the value through a function.
注意:这是一个丑陋且未经测试的黑客,我认为我永远不会这样做
我不确定 ViewData 是什么类型,所以我在这里使用了 Object,最好实际上更改实际代码中的类型。
这是通过将扩展方法挂在 System.Object 上来实现的,因此它始终可用于所有类型......丑陋,但它可以完成工作:
NOTE: This is an ugly and untested hack, I don't think I'd ever do this
I'm not sure what type ViewData is, so I used Object here, it would be best to actually change the type in the real code.
this works by hanging an extension method off System.Object, so it is always available on all types...ugly, but it may do the job: