Can I get to the database from a custom binder?

Let's say I have an object that receives some data from HttpPost and some from a database. I think I want to allow ModelBinder to go to the database / repository for the data that is not in the message. In practice, is this a good or bad idea?

+3
source share
6 answers

I decided to change my initial answer, given that my thinking about these things has developed since the beginning of 2010.

In my initial answer, I basically expressed that, although my instincts told me that you should not do this, it was inconvenient for me to say that we should not be unable to formulate why.

, , , , .

+6

. , . , , , . , . , , .

+4

, , .

- . IMHO " " MVC ActionFilter ModelBinder. , - . , .

, , , .

    //logic not in modelbinder
    public ActionResult Edit( KittyCat cat )
    {
        DoSomeOrthagonalDatabaseCall( cat );

        return View( new MODEL() );
    }

.

    //logic in model binder
    public ActionResult Add( KittyCat cat )
    {
        return View( new MODEL() );
    }
+2

MVC. ModelBinder , . - , . /, .

, , , -. - , , , , , .

, , , , . , , ModelBinder .

, , , , , , , .

+2

, .

: , .

+1

, . , , :

1- . , /. , .

2- , ASP.NET MVC Framework. , Binders?

, , "" Model Binders. , . . , . . "". :

public ActionResult Save(DocumentViewModel viewModel)
{
     if (!ModelState.IsValid)
     {
         viewModel.Categories = _repository.GetAll();
         return View(viewModel);
     }
}

I believe that initializing categories here is ugly and smells like code. What if you had several properties that needed to be populated from the database? What if you had more than one action with a DocumentViewModel as an argument? You will have to repeat this ugly step again and again. The best approach is to fill out all the model properties using the Binder module and pass it to the controller. Thus, the object that is transferred to the controller is in a “consistent” state.

+1
source

Source: https://habr.com/ru/post/1741574/


All Articles