How to gain control over model binding?

前端 未结 2 635
时光说笑
时光说笑 2021-01-02 05:30

I started using MVC recently and I\'m getting little disappointed. Instead of helping me, the framework is getting in my way.

I\'m trying to write a controller actio

2条回答
  •  醉梦人生
    2021-01-02 06:14

    You can leverage IModelBinder interface and write a complete custom model binder. Here it is explained well. Essentially, this interface exposes a method "BindModel", where you can control model binding behavior along with validation.

    http://www.dotnetcurry.com/ShowArticle.aspx?ID=584

    However, this might complicate the matter and you might get in spaghetti code. I would suggest a simple "Action per model", if it suites you. So you can write something like this :

    ActionResult SaveA(long id, AViewModel)
    {
          //.... Action to be conducted in case it is form A.
    }
    ActionResult SaveB(...., BViewModel)
    {
           //... Action to be conducted in case it is form B.
    }
    
    
    // Your view models can be structured for code reuse as well.
    class AViewModel {  ...  }
    class BViewModel : AViewModel {  ...  }
    

提交回复
热议问题