DisplayTemplate for an object in a ViewBag

I need to display the date stored in the ViewBag, and for this I need to use DisplayTemplate. Now, if it was a date in the model, I would use the DisplayFor helper, but how can I do this for the ViewBag?

I have the following:

Views \ Shared \ DateTime.cshtml

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

Index.cshtml

 @((DateTime)ViewBag.Date) 

controller

 ViewBag.Date = DateTime.Now 

What should I change in the view to display the ViewBag.Date in dd-MMM-yyyy format?

I know I can do this:

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

But in this case, I have to do this every time I want to display the date from the ViewBag, and what if I want to change the format? I will need to make a lot of changes.

+1
source share
3 answers

There is no overload of the mapping, which takes a value as an argument.

So.

You can just do

 @ViewBag.disp 

or (if it contains HTMl)

 @Html.Raw(ViewBag.disp) 

or if you want a TextBox

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

change date format for each item

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

ToShortDateString() explains to know more about this, hope helps someone.

+1
source

There is no display overload with parameter. Although there is a workaround that works great with any value. Create in your permission a partial name with the name _Value.cshtml the contents of the partial:

@ {

 Layout = null; 

}

@ Html.DisplayForModel ()

then on your page just call partial, like this:

@ Html.Partial ("_ Value", myValue)

and myValue will be displayed using a specific DisplayTemplate for this value type (DateTime, bool, or whatever other type you want)

0
source

Source: https://habr.com/ru/post/1348170/


All Articles