为什么viewmodel属性在表单帖子上执行访问器?

时间:2015-05-19 18:39:24

标签: .net asp.net-mvc

视图模型:

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

查看:

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

当执行上面的代码时,页面表明SomeProperty和SomeMethod都被执行了一次 当页面回发时,_SomePropertyExecuteCount的值表示在回发期间触发了SomeProperty的get访问器。所述吸气剂的断点证实了这一点。为什么在提交表单时访问getter?如果需要访问getter,为什么SomeMethod也不需要被访问?

0 个答案:

没有答案