[英]How do I use DisplayFor() for objects that are not directly part of my model in asp .net mvc 2?
I'm sure I'm missing something pretty simple here. 我确定我在这里遗漏了一些非常简单的东西。 I've created a custom DateTime display template.
我创建了一个自定义的DateTime显示模板。 This works fine when using:
使用以下方法时效果很好:
<%= Html.DisplayFor(x=>x.DateTimeProperty) %>
However, I have a situation where I am iterating over objects in the Model in a for loop while inside a partial control. 但是,有一种情况是我在部分控件内部的for循环中迭代Model中的对象。 I want a DateTime property to use the display template, but I can't figure out how to instruct it to do so.
我希望DateTime属性使用显示模板,但是我不知道如何指示它使用显示模板。 The property is a DateTime as it should be.
该属性应为DateTime。 The looks like:
看起来像:
<% foreach (var item in Model) { %>
<%= Html.Encode(item.DateTimeProperty) %>
<% } %>
I can't call Html.DisplayFor(...) because of this structure, but I want all DateTime properties to use my DateTime display template. 由于这种结构,我无法调用Html.DisplayFor(...),但我希望所有DateTime属性都使用我的DateTime显示模板。
I've tried adding a UIHint via DataAnotations, but that doesn't seem to have worked. 我尝试通过DataAnotations添加UIHint,但这似乎没有用。
How do I do this? 我该怎么做呢?
Not that this question got many views, but I found the answer and figured I'd post in case someone was curious. 并不是说这个问题有很多看法,但是我找到了答案,并认为如果有人好奇的话,我会发帖。
The solution was rather simple: 解决方案非常简单:
<%= Html.DisplayFor(x=>item.ReviewDate, "DateTime") %>
My custom Display template (named: DateTime) is defined as: 我的自定义显示模板(名为:DateTime)定义为:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<%
string value = (Model.HasValue ? Model.Value.ToShortDateString() : "");
%>
<%= Html.Encode(value) %>
I guess I didn't realize that when you declared the lambda, you didn't have to use the variable on the left side of the '=>' at all. 我想我没有意识到,当您声明lambda时,您根本不需要使用'=>'左侧的变量。 I always thought it was mandatory.
我一直认为这是强制性的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.