如何为 DisplayFor() 创建 MVC Razor 模板 [英] How do I create a MVC Razor template for DisplayFor()

查看:17
本文介绍了如何为 DisplayFor() 创建 MVC Razor 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型中有几个仅用于显示的属性,但我需要使用 jQuery 检索它们的值以在页面上执行计算.标准的 Html.DisplayFor() 方法只是将它们的值写入页面.我想创建一个剃刀模板,允许我将每个元素呈现为:

I have a couple of properties in my view model that are display-only but I need to retrieve their values using jQuery to perform a calculation on the page. The standard Html.DisplayFor() method just writes their value to the page. I want to create a razor template that will allow me to render each element as:

<span id="ElementsId">Element's value</span>

我知道我可以在 Html.DisplayFor() 中指定一个模板来使用特定模板来呈现属性,但在该模板中我如何识别 id 属性写入span 标签?

I know I can specify a template in Html.DisplayFor() to use a particular template for rendering the property but within that template how do I identify the id attribute to write into the span tag?

@Html.DisplayFor(model => model.Element, "MyTemplate");

推荐答案

好的,我找到了,其实很简单.在我的 ViewsSharedDisplayTemplates 文件夹中,我有 Reading.cshtml 包含以下内容:

OK, I found it and it's actually very simple. In my ViewsSharedDisplayTemplates folder I have Reading.cshtml containing the following:

@model System.Int32
<span id="@ViewData.ModelMetadata.PropertyName">@Model</span>

这使用属性名称作为 id 属性和属性值作为内容呈现正确的标签:

This renders the correct tag using the name of the property as the id attribute and the value of the property as the contents:

<span id="Reading">1234</span>

在视图文件中,可以使用以下方法调用:

In the view file this can be called using the following:

@Html.DisplayFor(model => model.Reading, "Reading")

或者,如果模型属性用 UIHint("Reading") 修饰,那么模板名称可以被排除在对 DisplayFor() 的调用之外,它仍然会使用模板渲染:

Or if the model property is decorated with UIHint("Reading") then the template name can be left out of the call to DisplayFor() and it will still render using the template:

@Html.DisplayFor(model => model.Reading)

这应该同样适用于自定义编辑器模板.

This should work equally well with custom editor templates.

这篇关于如何为 DisplayFor() 创建 MVC Razor 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆