Date field 01/01/0001

Asked

Viewed 4,237 times

7

I’m with a project who owns a View that has a field to receive a type DateTime. In the database this field is required.

The problem is that whenever I access the respective View, this field is filled with 01/01/0001, which obliges me to always delete it.

How can I make this field come in white?

Class ownership:

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

View property:

<p class="linha">
    <label class="w100" for="DataDaSolicitacaoDeSaida"> Data da solicitação de saída </label> 
    @Html.EditorFor(model => model.DataDaSolicitacaoDeSaida) 
</p>
  • Paste the View, Actionresult, and the Class that generates such a View please ?

  • 1

    Class property: [Datatype(Datatype.Date)] public System.Datetime Datetime Datetime Datedaddee { get; set; } View property <p class="line"> <label class="W100" for="> Output request date:</label> @Html.Editorfor(model => model.>

  • In all browsers gives it?

  • @Html.Textboxfor(model => model. ???

  • Yes, this is entered by the code itself

3 answers

6

You must set the property to nullable, and put the date-Annotation Required over the field.

As there is already another answer saying this, I will explain it in the most detailed way I can.

Nullable? That doesn’t make sense...

That makes sense yes... a view-model is a model that serves to exchange data between the controller and the view. If the view can appear with the value of the empty property when invoking the operation CRUD of creation, so it makes sense that this property is nullable, because this is the initial state, despite being invalid... fact this which is treated by Annotation Required hassle-free.

If you do not make the property nullable, then you cannot pass a view-model for the creation view (ie, is the same as pass null for the view)... to my mind 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, to 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 builder of MeuViewModel, already Initiating the default value.

Annotation Required

Required serves to say: if the value associated with the property is null, or empty, then the model is invalid. It doesn’t matter if the value of the property is cancellable or not. It turns out that validation can be done on the client, or on server. MVC 5 can use the attribute required to perform client-side validation which is not a rule. MVC 3 also has client validation. In all previous cases, whether nullable property or not, none conflict conceptual with the attribute Required.

Use Html.Editorfor

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

  • this method will generate HTML fields with template prefixes correctly, what is needed 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 data type. If you don’t like the way it was rendered, you can easily create an Editortemplate to get 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 and 5, TextBoxFor reads and renders the value of the property passed to it, unless the view-model passed is null.

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

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

Also, this method ignores all attempts to format it using Annotations: DisplayFormat, DataType, UIHint...

When to use Textboxfor

I see no reason to use this method. Never!

If you are going to use a date-Picker plugin, it requires a <input type="text" />, then use an Editortemplate, which moreover encapsulates the use of the plugin.

Do not use Html.Textbox

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

Reference

  • 1

    A large number of programmers still seek to avoid Viewmodel and do everything in their own domain classes when they use code-first.

  • 2

    Programming equals natural selection, agent never knows what’s best or worst until I tried and measure... I myself used domain classes in the view, and I didn’t have big problems, however, I always ended up needing something more in the views, and I had to go creating view-models to the extent necessary.

  • 2

    Using domain classes as being of vision, will turn into maintenance work, rather than creation work... only has a detail, maintenance is more boring (gives me less satisfaction) than creation, besides being more time consuming, because of the time needed to locate the class to be changed, and then by the work of verifying whether the change caused side effects or not... in short: I learned that creating vision classes separate from domain classes is good.

5

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

To resolve declare the property as below.

[Required]
public DateTime? MeuDateTime{ get; set; }
  • Yeah... that’s what I researched too. Check it out for us @user4849

  • Dear, as I said leaving the property as Nullable the capo generated no longer shows the date 01/01/0001. When the post is triggered I treat the date in the controller always checking if the date is different from 01/01/0001

  • You can let the nullable property along with the required attribute and in the check action ModelState.IsValid, instead of checking the value 01/01/0001... even because with the nullable property, this value will not appear again alone, unless typed by the user.

  • Using ASP.NET MVC 5 in VS.2013 I had the same problem.

1

Dear friends, I believe that every Storm of Ideas has its value, but, in the moment that comes and has a position of the radical type, I found myself in the right to expose the real solution to this doubt ...

The 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 Without Generating Data 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 between these two Controllers in the Actionresult Method Create is that one does not Model and the other sends a Model Instance (new person()) and that’s when Data gets 01/01/0001.

Controller Image without Generating Data 01/01/0001 inserir a descrição da imagem aqui

Controller Image with Date 01/01/0001 inserir a descrição da imagem aqui

Page Generated without 01/01/0001 inserir a descrição da imagem aqui

Page Generated on 01/01/0001 inserir a descrição da imagem aqui

I’ve asked him several times to put the code to that Actionresult, but, unfortunately, it never did. In conclusion, I did the same thing using concepts proposed by the tool, without the insertion of unnecessary code and, no longer seeking artifices to ratify my knowledge. The Solution perhaps proposed only matches the reality of our friend, but, for example, in my ASP.NET MVC Systems I never needed to make such code, because, I study the conceptual model before implementing ... I’m terribly sorry, but I have to propose in such a famous group that tests be prepared before anything else ...

Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.