Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is asp.net mvc model binder reading view model properties?

When I put a breakpoint on a getter of a property in my view model, asp.net core model binding is reading my property value. This is before the view model is used in the actual view. Is there a reason it is doing this? Model binding should be for setting the properties on your view model from the value provider, not for reading them from your view model. Is there a way to prevent this?

Edit: Since there is a vote to close this question due to not providing steps to easily reproduce, here they are. Create the following controller in an asp.net core project:

public class TestController : Controller
{
    public IActionResult Test(TestViewModel model)
    {
        return View(model);
    }

    public class TestViewModel
    {
        public string TestProperty
        {
            get
            {
                return "";
            }

            set
            {
                return;
            }
        }
    }
}

If you put your break point in the getter, and a break point in the test controller action, you will see that the getter is accessed before it actually enters the controller action to be consumed by the view. It doesn't seem like properties in your view model should be read at this point. Just look for ideas on why this is happening, and if it is possible (or a good idea) to prevent this behavior. Thanks!

like image 693
Jeremy Armstrong Avatar asked Nov 08 '22 11:11

Jeremy Armstrong


1 Answers

I'm not sure what version of MVC you're using, but in MVC version 5.2.3, the DefaultModelBinder calls the model class getters before setting the request values on each property during the binding process prior to the controller method being called. I could not figure out why it does this, but I was able to change that behavior by implementing a custom model binder based on the original DefaultModelBinder source code that removes the calls to the getters.

See a more detailed explanation and my full solution here: https://stackoverflow.com/a/54431404/10987278.

In your comments you mention you already have a custom model binder, so you might be able to just add the BindProperty(...) override from my solution to get the behavior you're after.

like image 64
Dave Slife Avatar answered Nov 15 '22 06:11

Dave Slife