简体   繁体   English

匿名对象中集合的格式化日期

[英]Formatting Date of a collection in an Anonymous Object

I got a business layer which returns an anonymous object which has a collection of rows which have dates. 我有一个业务层,该业务层返回一个匿名对象,该对象包含具有日期的行的集合。 I want to get regional formatting of the dates, but I don't want to pass the regional setting into the business layer, instead keeping the formatting in the Controller Action of the MVC website. 我想获取日期的区域格式,但是我不想将区域设置传递到业务层,而是将格式保留在MVC网站的Controller Action中。

Biz Layer: 商业层:

public object GetItems(int catID)
{
 var data = GetDbItems(catId).ToList();
 var Items = new 
         {
            total = data.Count(),
            page = 1,
            rows = (from c in data
                    select new {
                       ID = c.id,
                       Desc = c.desc,
                       CreationDate = c.CreationDate
                    })
         };

 return Items;
}

back in the Action Method of the controller I want to format the date in the collection inside of the anonymous type. 回到控制器的“操作方法”中,我想设置匿名类型内部集合中的日期格式。 How can I do this? 我怎样才能做到这一点?

public JsonResult GetItems(int catID)
{
 string cultureString = HttpContext.Request.UserLanguages.FirstOrDefault();
 DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture(cultureString).DateTimeFormat;
 var items = bizLayer.GetItems(catID);
 var test = from i in items
       select i.rows;  // ????  doesn't know about this collection yet.
 }

What I want to do. 我想做的事。

get at the rows collection of the anonymous type, find the date column and format it with 获取匿名类型的行集合,找到日期列并使用

CreateDate = c.CreateDate.ToString("d", dtfi)

I got a business layer which returns an anonymous object 我有一个业务层返回一个匿名对象

That's probably the first thing that needs to be fixed and replace this anonymous object by a strongly typed model which would greatly simplify the mapping of this domain model to a view model in order to perform the desired formatting. 这可能是第一件事,需要修复,并使用强类型模型替换该匿名对象,这将大大简化此域模型到视图模型的映射,以便执行所需的格式设置。

You can't. 你不能 You need to make a concrete class with the same properties as your anonymous object(s) and pass back a YourNewClass instead of an object . 您需要制作一个与匿名对象具有相同属性的具体类,然后传回YourNewClass而不是object

Why the business layer returns an anonymous object is certainly vague, you should fix that first. 为什么业务层返回匿名对象肯定是模糊的,您应该首先解决该问题。 But if you can't the best shot you've got is parsing each element as a DateTime; 但是,如果您无法获得最佳的拍摄效果,那就是将每个元素解析为DateTime。 and then reusing that information for the rest of the rows. 然后在其余行中重复使用该信息。

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

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