ViewBag中对象的DisplayTemplate

时间:2014-02-26 11:39:54

标签: c# asp.net-mvc-4

我需要显示存储在ViewBag中的日期,我需要使用DisplayTemplate。现在,如果它是模型中的日期,我将使用DisplayFor帮助器,但我如何为ViewBag做到这一点?

我所拥有的是以下内容:

视图\共享\ DateTime.cshtml

@model DateTime
@Html.Display("",Model.ToString("dd-MMM-yyyy"))

Index.cshtml

@((DateTime)ViewBag.Date)

控制器

ViewBag.Date = DateTime.Now

为了让ViewBag.Date以“dd-MMM-yyyy格式显示?”,我应该在视图中更改什么?

我知道我可以做到:

@(((DateTime)ViewBag.Date).ToString("dd-MMM-yyyy"))

但是在这种情况下,我每次想要从ViewBag显示日期时都必须这样做,如果我想更改格式怎么办?我将不得不做出很多改变。

3 个答案:

答案 0 :(得分:1)

没有Display的重载,它将值作为参数。

所以

你可以简单地做

@ViewBag.disp

或(如果它包含HTMl)

@Html.Raw(ViewBag.disp)

或者如果你想要一个TextBox

@Html.TextBox("disp", (string)@ViewBag.disp, new{@readonly = true})

答案 1 :(得分:1)

更改每个项目的日期格式

@foreach (var item in ViewBag.Balance)
{
@Convert.ToDateTime(item.StartDate).ToString("dd/MM/yyyy")
}

探索更多检查this,解释ToShortDateString(),希望帮助某人。

答案 2 :(得分:0)

显示器没有超载参数值。 虽然有一种解决方法可以正常使用任何值。 在您的sollution中创建一个名为_Value.cshtml的部分名称 部分内容是:

@ {

Layout = null;

}

@ Html.DisplayForModel()

然后在你的页面中简单地调用这样的部分:

@ Html.Partial(“_ Value”,myValue)

和myValue将使用定义的DisplayTemplate为这种类型的值(DateTime,bool或您想要的任何类型)呈现