Where to put the logic of views?

I am a little confused regarding ASP.NET MVC design patterns. I have a Masterpage, including a partial view that displays breadcrumbs:

<div id="header"> <strong class="logo"><a href="#">Home</a></strong> <% Html.RenderPartial("BreadCrumbs"); %> 

The fact is that I want links on packs to work both in production and in my environment. So my partial view code looks something like this:

 <p id="breadcrumbs"> You are here: <a href="http:// <% if (Request.Url.IsLoopback) Response.Write(String.Format("{0}/{1}", Request.Url.Host, Request.Url.Segments[1])); else Response.Write("http://mysite.com/"); ... 

Does this violate the principle of maintaining the view "stupid"? This principle was part of my argument for extracting this from the master page. I seem to have moved the problem to a new look? Which alternative?

+2
source share
2 answers

Not sure which version of MVC you are using. If you use MVC3, you can 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 can then add a property to your ViewBag (which is a dynamic object) called SiteUrl , in which you set the URL of the site depending on the state you are in.

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

+7
source

You can put a generation of crackers into the action of a child. This will give you a brand new View and Controller.

On the home page:

  <%: 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.

0
source

Source: https://habr.com/ru/post/1336159/


All Articles