ASP.NET MVC JsonResult Date Format

前端 未结 25 3248
渐次进展
渐次进展 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 12:02

    What worked for me was to create a viewmodel that contained the date property as a string. Assigning the DateTime property from the domain model and calling the .ToString() on the date property while assigning the value to the viewmodel.

    A JSON result from an MVC action method will return the date in a format compatible with the view.

    View Model

    public class TransactionsViewModel
    {
        public string DateInitiated { get; set; }
        public string DateCompleted { get; set; }
    }
    

    Domain Model

    public class Transaction{
       public DateTime? DateInitiated {get; set;}
       public DateTime? DateCompleted {get; set;}
    }
    

    Controller Action Method

    public JsonResult GetTransactions(){
    
    var transactions = _transactionsRepository.All;
            var model = new List<TransactionsViewModel>();
    
            foreach (var transaction in transactions)
            {
                var item = new TransactionsViewModel
                {
                    ...............
                    DateInitiated = transaction.DateInitiated.ToString(),
                    DateCompleted = transaction.DateCompleted.ToString(),
                };
    
                model.Add(item);
            }
            return Json(model, JsonRequestBehavior.AllowGet);
    }
    
    0 讨论(0)
提交回复
热议问题