Where to put view logic?

混江龙づ霸主 提交于 2019-12-06 07:19:09

Not sure what MVC version you are using. If you are using MVC3, you could create a GlobalActionFilter: http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx

public class ViewBagInjectionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnResultExecuting(filterContext);

        filterContext.Controller.ViewBag.SiteUrl = filterContext.HttpContext.Request.Url.IsLoopback
                                                       ? String.Format("{0}/{1}",
                                                                       filterContext.HttpContext.Request.Url.Host,
                                                                       filterContext.HttpContext.Request.Url.
                                                                           Segments[1])
                                                       : "http://mysite.com/";

    }
}

This filter could then add a property into your ViewBag (which is a dynamic object), called SiteUrl, in which you set the site url depending on the state you are in.

In your PartialView you would no longer need the if statement, and just call: ViewBag.SiteUrl . In addition any other page will have access to the SiteUrl property.

You could put the generation of the breadcrumbs in a child action. This will give you a whole new View and Controller

In the masterpage:

 <%: Html.Action("Crumbs", "Master") %>

MasterController:

 [ChildActionOnly]
 public PartialViewResult Crumbs() {
    if (Request.Url.IsLoopback()) {
       return PartialView("DebugCrumbs");
    } else {
       return PartialView("Crumbs");
    }
 }

Create a Crumbs and DebugCrumbs view that will be called local or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!