evictednoise evictednoise - 3 months ago 10
ASP.NET (C#) Question

ASPX - Why is the parameterless constructor invoked, skipping the parametered one?

This is the http request of browser

http://localhost:59440/CaseCards/Registrai/neigaliuju_registras.aspx?saliesId=5b8c3abc-4eec-4d69-b66a-25c7f27a2187


This is my code-behind file with two constructors

public NeigaliujuRegistras()
{

}

public NeigaliujuRegistras(string saliesId)
{
_saliesId = new Guid(saliesId);
//more of very secret bla bla
}


The following code makes the request

oWnd = radopen("CaseCards/Registrai/neigaliuju_registras.aspx?saliesId=" + $("input[name*='hsvSaliesId']").val(), "meow");


If I put breakpoints on both constructors, I see that upon laoding it goes into parameterless constructor, and the parametered one is never invoked.

This results in
_saliesID
having
{00000000-0000-0000-0000-000000000000}
value.

Why is the parameterless constructor invoked over parametered one?

Answer

This is the way how the ASP .Net framework creates these instances.

In your particular case you don't need this constructor since you can get the saliesId from Request.QueryString object. If you still want to have this in the constructor you can do something like this.

public NeigaliujuRegistras()
{
    // attach a handler to the Init event so to make sure the Request object is available.
    this.Init += (_o, _e) => {
         saliesId = new Guid(Request.QueryString["saliesId"]);
    };
}

Or you can follow the standard way placing the code in the Page_Load method.

protected void Page_Load(object sender, EventArgs e)
{
    saliesId = new Guid(Request.QueryString["saliesId"]);
}