{搞定;组;使用}在视图模型 [英] { get; set; } used in ViewModel

查看:119
本文介绍了{搞定;组;使用}在视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#与通过从控制器到视图的视图模型一个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; }

如此重要?

推荐答案

我不知道很多关于asp.net MVC /剃须刀,但你的2 code样本之间的一个重要区别。

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

创建一个属性,一旦编译,有在课堂生成的私人领域,与访问字段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;
        }
    }

但是以下内容:

public string Description;

创建一个简单的公共领域。

Creates a simple public field.

我的猜测是,剃须刀使用反射来从视图模型得到的值,它可能会寻找一个属性,而不是一个字段。因此,它决定了属性不存在,因此返回null

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

这篇关于{搞定;组;使用}在视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆