ASP.NET MVC JsonResult Date Format

前端 未结 25 3265
渐次进展
渐次进展 2020-11-21 11:22

I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:

return new JsonRes         


        
25条回答
  •  温柔的废话
    2020-11-21 11:45

    Format the date within the query.

    var _myModel = from _m in model.ModelSearch(word)
        select new { date = ((DateTime)_m.Date).ToShortDateString() };
    

    The only problem with this solution is that you won't get any results if ANY of the date values are null. To get around this you could either put conditional statements in your query BEFORE you select the date that ignores date nulls or you could set up a query to get all the results and then loop through all of that info using a foreach loop and assign a value to all dates that are null BEFORE you do your SELECT new.

    Example of both:

    var _test = from _t in adc.ItemSearchTest(word)
                            where _t.Date != null
                            select new { date = ((DateTime)_t.Date).ToShortDateString() };
    

    The second option requires another query entirely so you can assign values to all nulls. This and the foreach loop would have to be BEFORE your query that selects the values.

    var _testA = from _t in adc.ItemSearchTest(word)
                             select _i;
    
                foreach (var detail in _testA)
                {
                    if (detail.Date== null)
                    {
                        detail.Date= Convert.ToDateTime("1/1/0001");
                    }
                }
    

    Just an idea which I found easier than all of the javascript examples.

提交回复
热议问题