ArticleZip > Asp Net Mvc Jsonresult Date Format

Asp Net Mvc Jsonresult Date Format

ASP.NET MVC JsonResult Date Format

When working with ASP.NET MVC and returning JSON data from a controller action, you might encounter situations where you need to format dates in a specific way. In this guide, I'll show you how to handle date formatting in ASP.NET MVC when returning JsonResult objects.

Let's start with creating a simple JsonResult action method in a controller. Suppose you have a controller called HomeController with an action method that returns JSON data containing a DateTime property.

Csharp

public class HomeController : Controller
{
    public ActionResult GetDate()
    {
        var currentDate = DateTime.Now;
        return Json(new { Date = currentDate }, JsonRequestBehavior.AllowGet);
    }
}

By default, when you return a DateTime property in a JsonResult object, the date will be serialized using the default format. However, you might want to customize the date format before sending it to the client.

To change the date format in the JsonResult response, you can use a custom `JsonResult` class that overrides the `ExecuteResult` method. Here's an example of how you can create a custom `JsonResult` class to handle date formatting:

Csharp

public class CustomJsonResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (Data != null)
        {
            Data = new { Date = ((DateTime)Data).ToString("yyyy-MM-dd") };
        }
        base.ExecuteResult(context);
    }
}

Next, modify the ActionResult method in the controller to use the custom `JsonResult` class:

Csharp

public class HomeController : Controller
{
    public CustomJsonResult GetDate()
    {
        var currentDate = DateTime.Now;
        return new CustomJsonResult { Data = currentDate };
    }
}

With this setup, the date will be formatted as "yyyy-MM-dd" before being serialized into JSON. You can customize the date format by changing the format string in the `ToString` method.

Finally, don't forget to register the custom JsonResult class in the `Global.asax.cs` file in the `Application_Start` method:

Csharp

protected void Application_Start()
{
    ...
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
    ...
}

By adding the custom `JsonValueProviderFactory`, you ensure that the custom `JsonResult` class is used for returning JSON data across your ASP.NET MVC application.

In conclusion, formatting dates in ASP.NET MVC when returning JsonResult objects can be achieved by creating a custom `JsonResult` class and overriding the serialization logic. By following the steps outlined in this guide, you can seamlessly format dates according to your requirements in your ASP.NET MVC applications.

×