简体   繁体   English

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

[英]How do I create a MVC Razor template for 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.我的视图模型中有几个属性仅用于显示,但我需要使用 jQuery 检索它们的值以在页面上执行计算。 The standard Html.DisplayFor() method just writes their value to the page.标准的Html.DisplayFor()方法只是将它们的值写入页面。 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() 中指定一个模板来使用特定模板来呈现属性,但在该模板中我如何识别要写入span标签的id属性?

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

OK, I found it and it's actually very simple.好的,我找到了,其实很简单。 In my Views\\Shared\\DisplayTemplates folder I have Reading.cshtml containing the following:在我的Views\\Shared\\DisplayTemplates文件夹中,我有包含以下内容的Reading.cshtml

@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:这使用属性名称作为id属性和属性值作为内容呈现正确的标签:

<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:或者,如果模型属性使用UIHint("Reading")装饰,则模板名称可以不包含在DisplayFor()调用之外,它仍将使用模板进行渲染:

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

This should work equally well with custom editor templates.这应该同样适用于自定义编辑器模板。

I read many SO posts about defining template for @Html.DisplayFor for Boolean property but I couldn't clearly understand them.我阅读了许多关于为布尔属性定义@Html.DisplayFor模板的 SO 帖子,但我无法清楚地理解它们。 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 1. 创建模板

At first, you need to add a Partial View in path below (the path is very important):首先需要在下面的路径中添加一个Partial View (路径很重要):

Views/Shared/DisplayTemplates/

For example, I created a Partial View that named _ElementTemplate and Fill it like this:例如,我创建了一个名为_ElementTemplatePartial View并像这样填充它:

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

2. Adding UIHint to the Model 2. 在模型中添加UIHint

To make a connection between your property and template , you should add UIHint attribute like below in your model class:要在您的propertytemplate之间建立连接,您应该在模型类中添加如下所示的UIHint属性:

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

3. Using @Html.DisplayNameFor in View 3.在视图中使用@Html.DisplayNameFor

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) ):上面的代码在我的示例中呈现为下面的代码( if (MyProperty == true) ):

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

Setting attributes设置属性

For setting id or other html attributes you can use ModelMetadata like this:要设置id或其他 html 属性,您可以像这样使用ModelMetadata

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

Output with attribute带属性的输出

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

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

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

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

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.它会使 HTML id 属性成为运行时值,因此不能用设计时名称引用。

I used the overload of DisplayFor which allows you to add new objects onto the data dictionary (ViewBag)我使用了 DisplayFor 的重载,它允许您将新对象添加到数据字典 (ViewBag)

My model is a C# object called Project with various properties.我的模型是一个名为 Project 的 C# 对象,具有各种属性。 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.这是使用一个名为 StringDisplaySetHtmlID 的自定义模板,最后一个参数将一个键值对添加到 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.我使用了键名 HtmlID 而不仅仅是 ID 来避免潜在的常见命名冲突。

Now in my javascript I can pick up the span's content using the following jquery:现在在我的 javascript 中,我可以使用以下 jquery 获取 span 的内容:

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

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.使用@Html.DisplayTextFor(m => m)而不是@Model仍然会在呈现值时使用数据注释,而不是仅仅在其上运行ToString()
  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.在模型嵌套或重复的情况下,使用@Html.IdForModel()而不是@ViewData.ModelMetadata.PropertyName会更可取,并且 ID 不会只是属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM