名称的 Razor 子字符串
我需要获取名字的第一个首字母
我有以下内容:
@Html.DisplayFor(modelItem => item.FirstName.Substring(1,1))
但是当程序尝试运行它时,我收到以下错误:
模板只能用于字段访问、属性访问、单维数组索引或单维数组-参数自定义索引器表达式。
I need to get the first initial of the first name
I have the following:
@Html.DisplayFor(modelItem => item.FirstName.Substring(1,1))
I get the following error though when the program tries to run it:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需向您的视图模型添加一个属性:
然后:
如果您现在告诉我您没有使用视图模型,而是直接将域实体传递到视图(这是非常糟糕的设计),您可以使用自定义模板:
然后定义一个自定义显示模板
~/Views/Shared/DisplayTemplates/FirstLetter.cshtml
,其中包含以下内容:Simply add a property to your view model:
and then:
And if you now tell me that you are not using view models but are directly passing your domain entities to your views (which is very bad design), you might use a custom template:
and then you define a custom display template
~/Views/Shared/DisplayTemplates/FirstLetter.cshtml
with the following contents:你不能这样做,因为到你的卑鄙对象的映射不会像这样工作。就像异常消息告诉您只能将其与属性一起使用一样。
但是,您可以编写自己的 HtmlHelper 扩展来执行您想要的操作
You can't do this, because the mapping to your abject wont work like this. Like the exception message tells you you can only use it with properties.
You can however write your own HtmlHelper extension to do what you want
在substring之前,检查字符串的长度,否则会得到index out of range异常;
Before substring, check the length of the string, else you will get index out of range exception;