Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 为什么在表单post上执行viewmodel属性get访问器?_.net_Asp.net Mvc - Fatal编程技术网

.net 为什么在表单post上执行viewmodel属性get访问器?

.net 为什么在表单post上执行viewmodel属性get访问器?,.net,asp.net-mvc,.net,Asp.net Mvc,视图模型: public class IndexViewModel { public int _SomePropertyExecuteCount; public int _SomePropertySetValue; public int _SomeMethodExecuteCount; public int SomeProperty { get { return ++_

视图模型:

    public class IndexViewModel
    {
        public int _SomePropertyExecuteCount;
        public int _SomePropertySetValue;
        public int _SomeMethodExecuteCount;


        public int SomeProperty 
        { 
            get { return ++_SomePropertyExecuteCount; }
            set { _SomePropertySetValue = value;}
        }

        public int SomeMethod()
        {
            return ++_SomeMethodExecuteCount;
        }
    }
视图:

当执行上述代码时,页面指示SomeProperty和SomeMethod都执行了一次。

当页面发回时_SomePropertyExecuteCount的值表示在发回期间触发了SomeProperty的get访问器。上述getter上的断点证实了这一点。为什么在提交表单时访问getter?如果需要访问getter,为什么不需要访问SomeMethod?

从请求(post/get)数据创建对象后,将检查
ModelState
。我不确定整个流程,但默认的模型绑定器会启动调用。
@model ViewModelTest.Models.IndexViewModel

<div>
    <p>@String.Format("SomeProperty executed: {0} times.", Model.SomeProperty)</p>
    <p>@String.Format("SomeMethod executed: {0} times.", Model.SomeMethod())</p>

      <form action="/Home/Index" method="post">
        <button type="submit" value="Submit">Submit</button>
    </form>
</div>
    [HttpPost]
    public ActionResult Index(Models.IndexViewModel model)
    {
        int p =  model._SomePropertyExecuteCount;   // p is 1
        int s = model._SomePropertySetValue;        // s is 0
        int m =  model._SomeMethodExecuteCount;     // m is 0   

        Models.IndexViewModel someOtherViewModel = new Models.IndexViewModel();
        return View(someOtherViewModel);
    }