Reusable Domain Controls in MS MVC

by coatta 2/2/2012 9:39:00 AM

Most of the example code for MVC that I have seen out there isn't well-suited to creating re-usable UI components -- in particular components that are application specific, but may want to be used in multiple contexts within the applications. For example, a component that displays a list of customers might be used on a number of different pages within the application. But it is possible to build re-usable components of this sort, you just have to follow a few rules which help ensure that the component is not coupled to the page that it resides on.

So, the rules are:

  • View models should always include a field for the ID of the target element
  • Always use RenderPartial() - Links need to be rendered with Ajax.ActionLink()
  • Forms need to be rendered with Ajax.BeginForm()
  • Forms/Links need AjaxActions with the target element set appropriately

Components always need to render into a specific HTML element on the page. The container (the page using the control) determines where it wants the control to display and passes this in as a parameter. The component thus knows where it should be rendered, but is ignorant of anything else on the page. If the component needs to include other components as part of its display, these should be rendered via Html.RenderAction(). In this case, the component is acting as the container, and so it must determine which HTML element the sub-component will render into. Obviously, this should be an HTML element defined in its cshtml file.

In general, components should not include links that would navigate to completely new pages. Instead, these links should simply route back to controllers/actions that have been given to the component as parameters -- it is the container's job to deal with global navigation, not the component.

Related posts



<<  June 2024  >>

View posts in large calendar


My opinions are my own, but you can borrow them if you like.

© Copyright 2024

Sign in