How to standardize DateTime format for all type fields without using DisplayFor or EditorFor in MVC?

2

In many cases in the application we have to use something like:

@Html.Raw(item.data.ToString("dd/MM/yyyy"))

can not be DisplayFor nor EditorFor in any case and we have to show the Brazilian date format. How to standardize this at one time using MVC?

    
asked by anonymous 15.09.2016 / 20:50

2 answers

3
  

How to standardize this at one time using MVC?

Using DisplayFor and EditorFor . Anything other than that, considering only the Razor, is incorrect.

Another thing is to use only the date, not the hour ( DateTime , in this case, it has both components). In this case, decorate your Model with the data type ( [DataType] ) corresponding to the data only format ( DataType.Date ):

using System.ComponentModel.DataAnnotations;

public class SeuModel
{
    ...
    [DataType(DataType.Date)]
    public DateTime Data { get; set; }
    ...
}

Remembering that this causes <input type="date" /> , not <input type="text" /> , which does not have date formatting by browser default.

    
16.09.2016 / 15:01
3

Hello, I think it's a good practice to create a component that manages the text on the screen.

Example:

namespace IM.Framework.MVC
{
    using System;
    using System.Text;
    using System.Web.Mvc;

    public static partial class IMHelper
    {
        public static MvcHtmlString IMInputDate(this HtmlHelper html, string Id, string Caption, string PlaceHolder, int Size, DateTime Value)
        {
            var sb = new StringBuilder();
            sb.Append(GeraDiv(new string[] { "input-control", "text", "span" + Size.ToString() }));
            sb.Append(IMLabel(html, Id, Caption));
            sb.Append(String.Format("<input type='text' id='{0}' placeholder='{1}' value='{2}' class='inputPadrao inputDate' />",
                Id, PlaceHolder, Value));
            sb.Append(FechaTag("div"));

            return new MvcHtmlString(sb.ToString());
        }
    }
}

In the View use instead of

@Html.Raw(item.data.ToString("dd/MM/yyyy"))

use:

@IMHelper.IMInputDate("id_do_campo", "Título", 10, item.data)

Remembering that in IMInputDate I use code that depends on other functions not available here. But the idea is just to give a "Light".

    
15.09.2016 / 21:14