如何为 DisplayFor() 创建 MVC Razor 模板

发布于 2024-11-02 01:18:35 字数 403 浏览 1 评论 0原文

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

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

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

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

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>

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");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情魔剑神 2024-11-09 01:18:35

好的,我找到了,其实很简单。在我的 Views\Shared\DisplayTemplates 文件夹中,Reading.cshtml 包含以下内容:

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

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

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

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

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

或者如果模型属性用 UIHint("Reading") 修饰,则模板名称可以从对 DisplayFor() 的调用中省略,它仍然会使用模板进行渲染:

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

这应该与自定义编辑器模板同样有效。

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

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

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")

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.

月下凄凉 2024-11-09 01:18:35

我读了很多关于为布尔属性定义 @Html.DisplayFor 模板的帖子,但我无法清楚地理解它们。您的问题已结束,在掌握它之后,我决定添加一个新答案,包括实现该问题所需的所有步骤。这可能对其他人有帮助。

1.创建模板

首先需要在下面的路径中添加一个Partial View(路径很重要):

Views/Shared/DisplayTemplates/

比如我创建了一个Partial View名为 _ElementTemplate 并按如下方式填充:

<span>
    @(@Model ? "Yes" : "No")
</span>

2.将 UIHint 添加到模型

要在属性模板之间建立连接,您应该在模型类中添加UIHint属性,如下所示:

[UIHint("_YesOrNoTemplate")]
public bool MyProperty { get; set; }

3.在视图中使用 @Html.DisplayNameFor

在每个需要此属性的视图中,您可以使用下面的代码:

<div>
    @Html.DisplayFor(modelItem => item.MyProperty)
</div>

输出

在我的示例中,上面的代码将呈现为下面的代码(if (MyProperty == true)):

<div>
    <span>
        Yes
    </span>
</div>

设置属性

要设置 id 或其他 html 属性,您可以使用 ModelMetadata 像这样:

<span id="@ViewData.ModelMetadata.PropertyName">
    @(@Model ? "Yes" : "No")
</span>

带属性的输出

<div id="MyProperty">
    <span>
        Yes
    </span>
</div>

I read many SO posts about defining template for @Html.DisplayFor for Boolean property but I couldn't clearly understand them. Your question is closed to this and after grasping it, I decided to add a new answer including all steps needed for implementing that. It might be helpful for other people.

1. Creating a template

At first, you need to add a Partial View in path below (the path is very important):

Views/Shared/DisplayTemplates/

For example, I created a Partial View that named _ElementTemplate and Fill it like this:

<span>
    @(@Model ? "Yes" : "No")
</span>

2. Adding UIHint to the Model

To make a connection between your property and template, you should add UIHint attribute like below in your model class:

[UIHint("_YesOrNoTemplate")]
public bool MyProperty { get; set; }

3. Using @Html.DisplayNameFor in View

In every view that you need this property, you can use code below:

<div>
    @Html.DisplayFor(modelItem => item.MyProperty)
</div>

Output

The code above is rendered to code below in my example (if (MyProperty == true)):

<div>
    <span>
        Yes
    </span>
</div>

Setting attributes

For setting id or other html attributes you can use ModelMetadata like this:

<span id="@ViewData.ModelMetadata.PropertyName">
    @(@Model ? "Yes" : "No")
</span>

Output with attribute

<div id="MyProperty">
    <span>
        Yes
    </span>
</div>
白日梦 2024-11-09 01:18:35

您可以将此id作为视图模型的一部分,并在显示模板中使用它:

<span id="@Model.Id">@Html.DisplayFor(x => x.Value)</span>

You could make this id part of the view model and use it in the display template:

<span id="@Model.Id">@Html.DisplayFor(x => x.Value)</span>
虚拟世界 2024-11-09 01:18:35

一篇文章解释了Templates(显示 + 编辑器),以及 UIHint 属性。

There's an article explaining the Templates (Display + Editor) in Razor, and also the UIHint attribute.

念﹏祤嫣 2024-11-09 01:18:35

我遇到了与原始帖子完全相同的问题。

不确定最后的评论是否有效。它会使 HTML id 属性成为运行时值,因此不能用设计时名称引用。

我使用了 DisplayFor 的重载,它允许您将新对象添加到数据字典 (ViewBag) 中。

我的模型是一个名为 Project 的 C# 对象,具有各种属性。在我看来,我有这样的:

@Html.DisplayFor(model => model.ProjectName, "StringDisplaySetHtmlID", new { HtmlID = "project-name" })

这是使用名为 StringDisplaySetHtmlID 的自定义模板,最后一个参数将键值对添加到 Viewbag。

我的模板文件如下所示:

@model string
<span class = "display-field" id = "@(ViewBag.HtmlID)">@Model</span> 

我还在此处设置一个类以用于样式设置。我使用键名 HtmlID 而不仅仅是 ID 来避免潜在的常见命名冲突。

现在,在我的 javascript 中,我可以使用以下 jquery 获取跨度的内容:

var projectName = $('#project-name').text()

I had exactly the same issue as the original post.

Not sure the last comment is valid. It would make the HTML id attribute a run-time value and therefore cannot be referenced with a design time name.

I used the overload of DisplayFor which allows you to add new objects onto the data dictionary (ViewBag)

My model is a C# object called Project with various properties. In my view I have this:

@Html.DisplayFor(model => model.ProjectName, "StringDisplaySetHtmlID", new { HtmlID = "project-name" })

This is using a custom template called StringDisplaySetHtmlID and the last parameter adds a key value pair to the Viewbag.

My template file looks like this:

@model string
<span class = "display-field" id = "@(ViewBag.HtmlID)">@Model</span> 

I'm also setting a class here for styling purposes. I've used the key name HtmlID rather than just ID to avoid a potential common naming collision.

Now in my javascript I can pick up the span's content using the following jquery:

var projectName = $('#project-name').text()
残月升风 2024-11-09 01:18:35

构建将输出以下内容的显示模板的最佳方法:

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

将是这样的:

<span id="@Html.IdForModel()">@Html.DisplayTextFor(m => m)</span>

首次发布此问题时,这些帮助程序可能不存在,但这以两种方式建立在 David 的答案之上:

  1. 使用 @Html.DisplayTextFor( m => m) 而不是 @Model 在渲染值时仍然会使用数据注释,而不是仅仅在其上运行 ToString()
  2. 在模型嵌套或重复且 ID 不会简单地出现的情况下,使用 @Html.IdForModel() 而不是 @ViewData.ModelMetadata.PropertyName 会更好。是属性名称。

The best way to build a display template that will output the following:

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

Would be this:

<span id="@Html.IdForModel()">@Html.DisplayTextFor(m => m)</span>

These helpers may not have existed when this question was first posted, but this builds on David's answer in two ways:

  1. Using @Html.DisplayTextFor(m => m) instead of @Model will still utilize data annotations while rendering the value instead of just essentially running ToString() on it.
  2. Using @Html.IdForModel() instead of @ViewData.ModelMetadata.PropertyName would be preferable in cases where the model is nested or repeated, and the ID is not going to simply be the property name.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文