Field date 01/01/0001

7

I'm having a project

asked by anonymous 08.04.2014 / 15:30

3 answers

6

You should set the property to nullable, and place the data-annotation Required on the field.

As there is another answer saying this, I will explain in as detailed as I can.

Nullable? This does not make sense ...

This makes sense, yes ... a view-model is a model that serves to exchange data between the controller and the view. If the view may appear with the empty property value invoking the operation Creation CRUD, then it makes sense that this property is nullable, because this is the initial state, although it is invalid ... This fact is handled by annotation Required with no problems.

If you do not make the property nullable, then you can not view-model for the view of creation (that is, it is the same as passing null to the view) ... in my opinion seems acceptable, but I like to have control, so I always call the creation view like this:

return this.View(new MeuViewModel());

So when I need to pass some default value, for the creation view, I can do this:

// eu quero que a opção 'OpcaoDoUsuario' já venha checked, na view de criação
return this.View(new MeuViewModel { OpcaoDoUsuario = true });

Or else I could change the constructor of MeuViewModel , already initializing the default value.

Annotation Required

Required is used to say: if the value associated with the property is null or empty, then the template is invalid . It does not matter if the property value is annulable or not. It turns out that validation can be done on the client, or on the server. MVC 5 can use the required attribute to do client-side validation which is not a rule. MVC 3 also has client validation. In all previous cases, whether the property is nullable or not, none conflicts conceptual with the Required attribute.

Use Html.EditorFor

In view, use EditorFor . There are several reasons for this:

  • This method will generate HTML fields with template prefixes correctly, which is required when working with master-detail and with EditorTemplates.

  • This method will obey the formats indicated via annotation: DisplayFormat , DataType , among others.

  • This method will render the most appropriate controls to handle the type of data. If you do not like the way it was rendered, you can easily to create an EditorTemplate to work around the problem by using annotation UIHint("NomeDoEditorPersonalizado") .

Do not use Html.TextBoxFor

I can confirm that in both ASP.NET MVC 3 and 4, as in 5, TextBoxFor reads and renders the value of the property passed to it, unless the past view-model is null.

If the property is a DateTime , which is a value-type whose value default is 01/01/0001 00:00:00 so that's what will be rendered. If it is a int , the default value is 0 , in which case that is what will be rendered.

Only the default value of the type will be rendered if a value is set manually.

In addition, this method ignores all attempts to format it using annotations: DisplayFormat , DataType , UIHint ...

When using TextBoxFor

I do not see any reason to use this method. Never!

If you are going to use a date-picker plugin, which requires a <input type="text" /> , so use an EditorTemplate, which, in addition, encapsulates the use of the plugin.

Do not use Html.TextBox

Do not use the TextBox method to create a template field. This method does not take into account the use of the template prefix, which is required in master-detail type views, and the use of EditorTemplates editing templates when applicable ( ViewData.TemplateInfo.HtmlFieldPrefix ) .

Reference

09.04.2014 / 01:15
5

What happens is that even though it is null, the date field will have a value, in this case, 01/01/0001.

To resolve declare the property as below.

[Required]
public DateTime? MeuDateTime{ get; set; }
    
08.04.2014 / 16:19
1

Dear friends, I believe that every Idea Storm has its value, but the moment it comes and it has a radical type of positioning, I have seen myself in the right to expose the real solution to this doubt ...

A Class

public class Pessoa
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public String Nome { get; set; }

    [DataType(DataType.Date)]
    public DateTime DataAniversario { get; set; }
}

Following the same field type and the same DataType

Controller No Generate Date 01/01/0001

public class PessoasController : Controller
    {
        //
        // GET: /Pessoas/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Criar()
        {
            return View();
        }
    }

Controller with Date 01/01/0001

public class PessoasController : Controller
    {
        //
        // GET: /Pessoas/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Criar()
        {
            return View(new Pessoa());
        }
    }

The difference of these two Controller in the ActionResult Create Method is that one does not send Model and the other sends a Model Instance ( new Person () ) and at that moment it is that the Date becomes 01/01/0001 .

Image of Controller without Generating Date 01/01/0001

ControllerImagewithDate01/01/0001

Page Generated No 01/01/0001

PageGenerated01/01/0001

I asked him several times to put the code for that ActionResult , but unfortunately he never put it. In conclusion, I did the same thing using concepts proposed by the tool, without the insertion of unnecessary code and more not looking for artifacts to ratify my knowledge. The solution maybe proposed only matches the reality of our friend, but, for example, in my MVC ASP.NET Systems I never needed to do such code, because, I study the conceptual model before implementing ... I ask a thousand excuses, but, I have to propose in a group so famous that tests are written before anything else ...

Thank you!

    
09.04.2014 / 17:18