开发者

mvc and partials is this not breaking the mvc pattern?

I have a partial view that displays a search options like search by category, region, date etc. This exists on every page. The partial uses a viewmodel containing lists of regions, cats etc.

As this is being used on every page - I have to load these properties on the viewmodel in every action in my controllers to ensure the data is available to the partial view. Not that happy with that. (Have simply used inherited viewmodels)

I see the partial can call a rende开发者_如何学Craction method on the controller to get the data, but now I would have a view calling data from a controller - breaking the mvc pattern.

what are other people doing in this situation?


You can use custom ActionFilters to inject common functionality to your actions/controllers to avoid repeating the same code.

For example :

public class RequiresSearchOptions : ActionFilterAttribute {
    public override void OnResultExecuting(ResultExecutingContext filterContext){
        filterContext.Controller.ViewData["SearchOptions"] =
            GetSearchOptions();

        //Or manipulate the model :
        //YourViewModel m = 
        //    (YourViewModel)filterContext.Controller.ViewData.Model;
        //m.SearchOptions = GetSearchOptions();
    }
}

And then decorate your actions/controllers.

[RequiresSearchOptions]
public ActionResult Index() {
    return View();
}
//or
[RequiresSearchOptions]
public class HomeController : Controller {
    //Actions
}


For a while I have used partial requests to render reused widgets. In my opinion they are are a more MVC way of rendering widgets over RenderAction as they don't require the View to know what action is being called.

My partial requests render partial views so your existing code can be easily migrated. They can also be output cached in the same way as any asp.net mvc action.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜