Gabc Gabc - 2 months ago 20
ASP.NET (C#) Question

Initialize values in Model asp.net c#

I have a Asp.net application in Visual studios in my model I have this class

public class Goalkeeper
{
public static string Name { get; set; }
public static string Position { get; set; }
public static int Matches { get; set; }
public static int Cleansheets { get; set; }
}


Is there a way for me to set the values of these in the model so I can use thme in all my different views and controller actions so I dont have to set them like this for example (Goalkeeper.Matches = 234;) In every single action in my controller, because that seems very inefficient.

Answer

You can either:

Add a constructor to your Model, where you set the initial values:

public class Goalkeeper
{
    public Goalkeeper() {
        Position = "Goalkeeper";
        Matches = 5;
        Cleansheets = 0;
    }

    public static string Name { get; set; }
    public static string Position { get; set; }
    public static int Matches { get; set; }
    public static int Cleansheets { get; set; }
}

Or, initialize the properties directly:

public class Goalkeeper
{ 
    public static string Name { get; set; }
    public static string Position { get; set; } = "Goalkeeper";
    public static int Matches { get; set; } = 5;
    public static int Cleansheets { get; set; } = 0;
}