我如何创建一个DisplayFor MVC剃刀模板() [英] How do I create a MVC Razor template for DisplayFor()
问题描述
我有一对夫妇在我的视图模型是只显示属性,但我需要使用jQuery进行网页上的计算来获取它们的值。该标准的 Html.DisplayFor()的方法,只是他们的值写入页面。我想创建一个模板,剃须刀,让我来呈现每个元素为:
<跨度ID =ElementsId>元素的值和LT; / SPAN>
我知道我可以在指定的 Html.DisplayFor()的使用特定模板呈现属性,但该模板我怎么确定的标识的属性中的模板写入的范围的标签?
@ Html.DisplayFor(型号=> model.Element,MyTemplate的);
OK,我发现它和它其实很简单。在我的视图\\共享\\ DisplayTemplates 的文件夹,我的 Reading.cshtml 的包含以下内容:
@model System.Int32
<跨度ID =@ ViewData.ModelMetadata.PropertyName> @模型与LT; / SPAN>
这使得使用属性为的标识的属性,该属性为内容的值的名称正确的标记:
<跨度ID =阅读与GT; 1234 LT; / SPAN>
在视图文件这可以通过调用以下内容:
@ Html.DisplayFor(型号=> model.Reading,读书)
或者,如果模型属性装饰着的 UIHint(读书)的那么模板名称可以被排除在通话来的 DisplayFor()的,它仍然会渲染使用模板:
@ Html.DisplayFor(型号=> model.Reading)
这应与自定义编辑模板,工作得很好。
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");
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.
这篇关于我如何创建一个DisplayFor MVC剃刀模板()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!