Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

asp.net mvc - { get; set; } used in ViewModel

I am using c# along with a ViewModel that passes the view model from the controller to the view.

In my view model, the following seems to work as expected as it passes the Description information from the view back to the controller:

    public string Description { get; set; } 

But if I have the following, it won't pass back the Description. Description shows null

 public string Description  

Why is the { get; set; }

so important?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I dont know much about asp.net MVC / Razor, but there is an important difference between your 2 code samples.

public string Description { get; set; }  

Creates a property, once compiled, there is a generated private field in the class, with get/set methods that access the field. A property declared with {get;set;} is the equivalent of:

    private string _description;
    public string Description
    {
        get
        {
            return _description;
        }
        set
        {
            this._description = value;
        }
    }

However the following:

public string Description;

Creates a simple public field.

My guess is that razor uses reflection to get values from the ViewModel, and it probably looks for a property, not a field. So it determines that the property does not exist, hence returning null


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...