Gabc
Gabc

Reputation: 89

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.

Upvotes: 1

Views: 5272

Answers (2)

R.jauch
R.jauch

Reputation: 103

Depending on the version of C# you are using you can initialize the property like this:

public static string Name { get; set; } = "Whatever";

This only works in C# 6 though

Upvotes: 4

nsevens
nsevens

Reputation: 2835

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;
}

Upvotes: 4

Related Questions