ASP> Pure Secondary Partial MVC Elements

Having been working with .net in both winforms and ASP.net for several years, I begin to enter MVC (I know a little late). One of the main confusion for me is the concept of reusable "components", similar to the concept of user control in web forms.

For example, I would like to have several “widgets” in the members area of ​​my site, one of which is detailed information about the registered user account manager. I can create this as partial, however, when the page loads the data that needs to be passed as part of the ViewModel / View Data. I would like to use this widget in several different sections, which would then mean that I need to pass code to transfer data to several different controllers. Does this seem to violate the DRY principle, or am I missing something here? Ideally, I would like everything to be encapsulated within 1 part, which can then be used on any page.

+7
source share
1 answer

You can do three ways:

1) For simple controls without much logic, you can create a new instance of a custom view model for the control: Html.RenderPartial ("YourControl", new YourControlViewModel () {Param1 = "value1", Param2 = Model.AnotherValue});

2) If you need rear-end logic for control, you can use Html.RenderAction ("ActionName", "SomeControllerName", RouteValuesDictionary); It will call the standard action of the controller, use the view and paste the result back into the page. You can add the [ChildActionOnly] attribute to the controller method to ensure that the method will be available only from Html.RenderPartial. It violates the MVC principle somewhat (view should not call the controller), but it is great for widgets and is used in the Ruby on Rails world without any problems. You can check out the excellent article from Haacked

3) Create your own html helper for tasks like date formatting, calculation, etc.

In your case, I would choose number two.

+4
source

All Articles