Why does the viewmodel property get an accessory being executed on a form post?

ViewModel:

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

      

View:

@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>

      

Controller:

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

      

When executing the above code, the page indicates that both SomeProperty and SomeMethod were executed once.
When the page is posted back, the _SomePropertyExecuteCount value indicates that the get Accessor for SomeProperty is fired during postback. A breakpoint on the indicated getter confirms this. Why is the recipient getting access when the form is submitted? If the getter needs to be accessed, why doesn't SomeMethod need to also be accessed?

+3


source to share





All Articles