As I understand it, in ASP.NET MVC a httprequest
is mapped to a controller/action.
- As one request is used to get one web page, could we call to these controllers "
page controllers
"?
My other question is about widgets (user controls) and RenderPartial
method:
- If a widget represents a classic ASP.NET
webcontrol
orusercontrol
, and I want to render this widget in a lot of pages, how could I 开发者_如何学Goavoid repeating the logic of the widget if this logic is in the "page controller
"?
As one request is used to get one web page, could we call to these controllers "page controllers"?
Why would you? They're named controllers. After all, an action on a controller doesn't neccessarily serve a "web page", it might respond using JSON data, XML, RSS or only a part of a web page (a 'control' if you want).
If a widget represent a classic asp.net webcontrol or usercontrol, and i want to render this widget in a lot of pages, how could avoid repeat the logic of the widget if this logic is in the "page controller"?
- Make sure your (business) logic is not in the controller: it doesn't belong there. The controller's job is to map input/output, not to handle logic.
- The views that contain your widget should have a
ViewModel
which contains the ViewModels needed in the widgets, e.g.
-
MainViewModel
{
UserWidgetViewModel UserViewModel;
List<Foo> Bar;
// ...
}
UserWidgetViewModel
{
string UserName;
int Reputation;
//...
}
I felt this unelegant first, but I've been using this for some time now and I believe it nicely encapsulates the necessary data.
Hope that helps
hmm I think you need to revise your understanding of the controllers. A controller has several method. It is not a controller that maps to an page, but the ActionMethods.
When calling RenderPartial, it is entering the corresponding ActionMethod (and that method could be on any controller) which is returning a PartialView (.ascx) rendered at the place you called it on the calling View (.aspx or another .ascx if you have multiple level of partial views). No logic is duplicated there... Or maybe I don't understand your question?
You could try a widget controller. It makes use of the new Html.RenderAction method in .NET MVC 2. Yes it technically breaks the pure mvc pattern (well done MS), but for practical purposes you might find it quite useful.
精彩评论