开发者

ASP.NET MVC ViewModelBuilder Suggestions

开发者 https://www.devze.com 2022-12-30 14:17 出处:网络
For anything but trivial view models, I use a view model builder that handles the responsibility of generating the view model object. Right now, I use constructor injection of the builders into my con

For anything but trivial view models, I use a view model builder that handles the responsibility of generating the view model object. Right now, I use constructor injection of the builders into my controllers but this smells a little since the builder is r开发者_运维知识库eally dependent upon which action method is being executed. I have two ideas in mind. The first one would involve a custom ActionFilter allowing me to decorate each action method with the appropriate builder to use. The second would be to add an override of the View method that is open to accepting a generic.

This is what my code currently looks like. Note, the builder get injected via the ctor.

    [HttpGet, ImportModelStateFromTempData, Compress]
    public ActionResult MyAccount()
    {
        return View(accountBuilder.Build());
    }

Here is what option one would look like:

    [HttpGet, ImportModelStateFromTempData, Compress, ViewModelBuilder(typeof(IMyAccountViewModelBuilder)]
    public ActionResult MyAccount()
    {
        return View();
    }

Or option two:

    [HttpGet, ImportModelStateFromTempData, Compress]
    public ActionResult MyAccount()
    {
        return View<IMyAccountViewModelBuilder>();
    }

Any thoughts or suggestions would be great!


TheBuilder

I think you could move the responsibility of construct the correct view model to the builder. and you could pass the ViewModel type you want to build as a parameter, something like:

[HttpGet, ImportModelStateFromTempData, Compress]
public ActionResult MyAccount()
{
   return View( AccountBuilder.Build<MyAccountViewModel>( ) );
}

About candidates

FirstOptionThis

the above approach allows you to have more flexibility in the view you will render inside the action (what happens if your controller should choose between 3 views to show, and each one has a different view model? Filter solutions start to get complex.)

SecondOption

The View method responsibility is to take the model and render the view using it. it's the controller responsibility to build the model. so being a little orthodox, I would recommend to avoid putting model building logic in the View method : ).


If you are asking for an opinion, now seeing your code, I would give my vote to your first option. I have used action filters that way extensively and it's nice - everything is in one place, enables easy decoratable actions, etc.


Your view model action filter could look at the expected model type on the ViewContext instead of requiring it in the attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消