How can I change "get" and "set" to a Property Model?

I currently have a DateTime property for the model. I use the telerik MVC framework, but I use the DateTime property, and the editor column for this property is auto-generated, so there is no code that controls it in my view or controller. There are instructions on the Telerik website on how to set a default date time for selecting a date, but this picker is not triggered anywhere because it is in a column. The problem is that I want to set DateTime as the current date and time, if one is not already specified. Currently, the model code is as follows:

public DateTime CreatedDate { get; set;} 

I want him to do something more:

 public DateTime CreatedDate { get { if (QuestionID != 0) { return this.CreatedDate; } else { return DateTime.Now; } } set { CreatedDate = value; } } 

this way it will return the DateTime that is stored for this Question if an ID exists. If you create a new question, it gets the current DateTime value.

The problem here is with Set. When I try to load the screen, install Get Stack Overflow. I am really informal with such code, so I have no idea how to work with it.

Before we did not work with the model and instead used jQuery to get CreatedDate data and set it to the current time. The problem is that when you go to the date picker part, it goes to the default date date, not the current one. so I want to install it through Model, View or Controller, and not with jQuery.

Let me know if you can help me understand what is happening with Gets and Sets in the model!

+4
source share
1 answer

You need to have private property that you use behind the scenes.

  private DateTime _createdDate; public DateTime CreatedDate { get { if (QuestionID != 0) { return _createdDate; } else { return DateTime.Now; } } set { _createdDate = value; } } 

You get overflow because now you are doing something like this:

 CreatedDate = 1/1/2012; ...which then calls CreatedDate = 1/1/2012; ...which then calls CreatedDate = 1/1/2012 ..You get the point (it is continuously setting itself until the stack overflows) 

Automatically implemented properties ( {get;set;} ) actually use a private variable behind the scenes. If you looked at IL, then you will see that it actually splits this simple {get;set;} into getter / setter based on the generated private variable. They are just a type of “compiler magic” to shorten boilerplate code to create a private variable if there is no real logic in the getter / setter. If you have logic, you need to implement this personal variable yourself.

+4
source

Source: https://habr.com/ru/post/1403513/


All Articles