Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...