Code background:
I have a model class in Asp.Net Core like this:
namespace urlShortner.Models
{
public class urlData
{
public string longUrl {get; set;}
public string shortUrl {get; set;}
public int hitTimes {get; set;} = 0;
public string creationTimeStamp {get; set;}
}
}
Now, if use Auto-Implemented property in ViewModel class to store POST request fields directly on it, it's ok, as below:
Razor Page:
<input asp-for="urlDataObj.longUrl">
.
.
.
<p style="color: white;">
@ViewData["lo"]
</p>
ViewModel:
[BindProperty]
public urlShortner.Models.urlData urlDataObj {get; set;}
public void OnPost()
{
ViewData["lo"] = urlDataObj.longUrl;
}
As shown above, I have a Auto-Implemented property that decorated by [BindProperty] attribute and Razor Page POST data to one of it's field directly, later than it'll be visible on page using ViewData.
I'm trying to avoid this, as it's a security concern and user can easily manipulate the form on the page to POST data for another field/s.
I changed the codes as below:
Razor Page(Changed):
<input asp-for="longUrl">
.
.
.
<p style="color: white;">
@ViewData["lo"]
</p>
ViewModel(Changed):
[BindProperty]
public string longUrl {get; set;}
public urlShortner.Models.urlData urlDataObj {get; set;}
public void OnPost()
{
ViewData["lo"] = longUrl; // POST data is OK!
urlDataObj.longUrl = longUrl; // Null reference exception will occurs!
}
Now if I use an Object of type urlShortner.Models.urlData instead of Auto-Implemented property like this:
public urlShortner.Models.urlData urlDataObj = new urlShortner.Models.urlData();
problem will be solved!
Question:
I can simply think this Auto-Implemented property will create baking field sometimes after program compilation, but know nothing when, how etc.
Also, why is it okay to fill the property by POST data, but assign it with a variable is not?
please explain it (life cycle) in clear.