/// <summary>
        /// The home.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Home(RenderModel model)
        {
            var home = model.As<Home>();

            var viewModel = new RenderPageBase<Home>(home);

            return this.View("~/Views/Home.cshtml", viewModel);
        }
		public static object Eval(string name, List<string> arguments, RenderModel model, RenderContext context)
		{
			Delegate func;
			if(!context.Functions.TryGetValue(name, out func))
			{
				func = BuiltInFunctions.GetFunction(name, context);
			}

			if(func == null)
			{
				throw new TemplateException("Invalid function: " + name);
			}

			var values = ConvertFuncParameters(name, func.Method, arguments, model, context);
			return func.DynamicInvoke(values);
		}
Exemple #3
0
        /// <summary>
        /// The index <see cref="ActionResult"/>.
        /// </summary>
        /// <param name="model">
        /// The current render model.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public override ActionResult Index(RenderModel model)
        {
            var viewModel = ViewModelFactory.CreateWishList(model);

            return(this.View(viewModel.ThemeViewPath("WishList"), viewModel));
        }
        private ActionResult RenderByTagOrCategory(RenderModel model, int?p, string tagGroup, string baseUrl)
        {
            var tagPage = model.Content as ArticulateVirtualPage;

            if (tagPage == null)
            {
                throw new InvalidOperationException("The RenderModel.Content instance must be of type " + typeof(ArticulateVirtualPage));
            }

            //create a blog model of the main page
            var rootPageModel = new ListModel(model.Content.Parent);

            var contentByTag = Umbraco.GetContentByTag(
                rootPageModel,
                tagPage.Name,
                tagGroup,
                baseUrl);

            //this is a special case in the event that a tag contains a '.', when this happens we change it to a '-'
            // when generating the URL. So if the above doesn't return any tags and the tag contains a '-', then we
            // will replace them with '.' and do the lookup again
            if (contentByTag == null && tagPage.Name.Contains("-"))
            {
                contentByTag = Umbraco.GetContentByTag(
                    rootPageModel,
                    tagPage.Name.Replace('-', '.'),
                    tagGroup,
                    baseUrl);
            }

            if (contentByTag == null)
            {
                return(new HttpNotFoundResult());
            }

            if (p == null || p.Value <= 0)
            {
                p = 1;
            }

            //TODO: I wonder about the performance of this - when we end up with thousands of blog posts,
            // this will probably not be so efficient. I wonder if using an XPath lookup for batches of children
            // would work? The children count could be cached. I'd rather not put blog posts under 'month' nodes
            // just for the sake of performance. Hrm.... Examine possibly too.

            var totalPosts = contentByTag.PostCount;
            var pageSize   = rootPageModel.PageSize;
            var totalPages = totalPosts == 0 ? 1 : Convert.ToInt32(Math.Ceiling((double)totalPosts / pageSize));

            //Invalid page, redirect without pages
            if (totalPages < p)
            {
                return(new RedirectToUmbracoPageResult(model.Content.Parent, UmbracoContext));
            }

            var pager = new PagerModel(
                pageSize,
                p.Value - 1,
                totalPages,
                totalPages > p ? model.Content.Url.EnsureEndsWith('/') + (p + 1) : null,
                p > 1 ? model.Content.Url.EnsureEndsWith('/') + (p - 1) : null);

            var listModel = new ListModel(tagPage, contentByTag.Posts, pager);

            return(View(PathHelper.GetThemeViewPath(listModel, "List"), listModel));
        }
 public override ActionResult Index(RenderModel model)
 {
     return(DocumentView(GetViewModel(model), model));
 }
 public override ActionResult Index(RenderModel model)
 {
     //Do some stuff here, then return the base method
     return(CurrentTemplate(this.CurrentContent));
 }
        public JsonResult Render()
        {
            try
            {
                var response = new RenderModel()
                {
                    Nodes = new List <GraphNode>()
                    {
                        new GraphNode
                        {
                            Id    = CLUSTER_NAME,
                            Group = 0
                        }
                    },
                    Links = new List <GraphLink>()
                };

                if (_cluster.AllNodes != null)
                {
                    int i = 1;

                    foreach (var node in _cluster.AllNodes.Values)
                    {
                        response.Nodes.Add(new GraphNode()
                        {
                            Id    = node.Name,
                            Group = i
                        });

                        response.Links.Add(new GraphLink()
                        {
                            Source = CLUSTER_NAME,
                            Target = node.Name,
                            Value  = 9
                        });

                        for (var k = 0; k < node.ActorsCount; k++)
                        {
                            var clusterNodeName = string.Format("Actor #{0} of node {1}", k, node.Name);
                            response.Nodes.Add(new GraphNode()
                            {
                                Id    = clusterNodeName,
                                Group = i
                            });

                            response.Links.Add(new GraphLink()
                            {
                                Source = node.Name,
                                Target = clusterNodeName,
                                Value  = 1
                            });
                        }

                        i++;
                    }
                }

                return(Json(response));
            }
            catch (Exception e)
            {
                _logger.Error(e);
                return(Json(null));
            }
        }
        /// <summary>
        /// The index <see cref="ActionResult"/>.
        /// </summary>
        /// <param name="model">
        /// The current render model.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public override ActionResult Index(RenderModel model)
        {
            var viewModel = ViewModelFactory.CreateBasket(model, Basket);

            return(View(viewModel.ThemeViewPath("Basket"), viewModel));
        }
 /// <summary>
 /// The default action to render the front-end view
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public virtual ActionResult Index(RenderModel model)
 {
     return(CurrentTemplate(model));
 }
Exemple #10
0
        public ActionResult Index(RenderModel model, int page = 1)
        {
            var customModel = new FileUploaderModel(model.Content);

            return(CurrentTemplate(customModel));
        }
 public ActionResult Index(RenderModel model, int productID)
 {
     return(RenderView(false));
 }
    private void SetModel(string renderModelName)
    {
        if (!models.Contains(renderModelName))
        {
            Debug.Log("Loading render model " + renderModelName);

            var vr = SteamVR.instance;
            if (vr == null)
                return;

            var renderModel = new Valve.VR.RenderModel_t();
            if (!vr.hmd.LoadRenderModel(renderModelName, ref renderModel))
            {
                Debug.LogError("Failed to load render model " + renderModelName);
                return;
            }

            var vertices = new Vector3[renderModel.unVertexCount];
            var normals = new Vector3[renderModel.unVertexCount];
            var uv = new Vector2[renderModel.unVertexCount];

            var type = typeof(Valve.VR.RenderModel_Vertex_t);
            for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
            {
                var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
                var vert = (Valve.VR.RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

                vertices[iVert] = new Vector3(vert.vPosition.v[0], vert.vPosition.v[1], -vert.vPosition.v[2]);
                normals[iVert] = new Vector3(vert.vNormal.v[0], vert.vNormal.v[1], -vert.vNormal.v[2]);
                uv[iVert] = new Vector2(vert.rfTextureCoord[0], vert.rfTextureCoord[1]);
            }

            int indexCount = (int)renderModel.unTriangleCount * 3;
            var indices = new short[indexCount];
            Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

            var triangles = new int[indexCount];
            for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
            {
                triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
                triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
                triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
            }

            var mesh = new Mesh();
            mesh.vertices = vertices;
            mesh.normals = normals;
            mesh.uv = uv;
            mesh.triangles = triangles;

            var textureMapData = new byte[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight * 4]; // RGBA
            Marshal.Copy(renderModel.diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

            var colors = new Color32[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight];
            int iColor = 0;
            for (int iHeight = 0; iHeight < renderModel.diffuseTexture.unHeight; iHeight++)
            {
                for (int iWidth = 0; iWidth < renderModel.diffuseTexture.unWidth; iWidth++)
                {
                    var r = textureMapData[iColor++];
                    var g = textureMapData[iColor++];
                    var b = textureMapData[iColor++];
                    var a = textureMapData[iColor++];
                    colors[iHeight * renderModel.diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                }
            }

            var texture = new Texture2D(renderModel.diffuseTexture.unWidth, renderModel.diffuseTexture.unHeight, TextureFormat.ARGB32, true);
            texture.SetPixels32(colors);
            texture.Apply();

            models[renderModelName] = new RenderModel(mesh, texture);

            vr.hmd.FreeRenderModel(ref renderModel);
        }

        var model = models[renderModelName] as RenderModel;
        GetComponent<MeshFilter>().mesh = model.mesh;
        GetComponent<MeshRenderer>().material = model.material;
    }
 public ActionResult Index(RenderModel model)
 {
     return(RenderView(false));
 }
Exemple #14
0
        /// <summary>
        /// The index <see cref="ActionResult"/>.
        /// </summary>
        /// <param name="model">
        /// The current render model.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public override ActionResult Index(RenderModel model)
        {
            var viewModel = ViewModelFactory.CreateProductGroup(model);

            return(this.View(viewModel.ThemeViewPath("ProductGroup"), viewModel));
        }
Exemple #15
0
        /// <summary>
        /// The default action to render the front-end view
        /// </summary>
        /// <param name="model"/>
        /// <returns/>
        public async new Task <ActionResult> Index(RenderModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var viewModel = new JobAdvertViewModelFromUmbraco(model.Content).BuildModel();

            // Add common properties to the model
            var expiryDate   = new ExpiryDateFromExamine(model.Content.Id, ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"], new ExpiryDateMemoryCache(TimeSpan.FromHours(1)));
            var modelBuilder = new BaseViewModelBuilder(new EastSussexGovUKTemplateRequest(Request, webChatSettingsService: new UmbracoWebChatSettingsService(model.Content, new UrlListReader())));
            await modelBuilder.PopulateBaseViewModel(viewModel, model.Content, new ContentExperimentSettingsService(),
                                                     expiryDate.ExpiryDate,
                                                     UmbracoContext.Current.InPreviewMode);

            modelBuilder.PopulateBaseViewModelWithInheritedContent(viewModel,
                                                                   new UmbracoLatestService(model.Content),
                                                                   new UmbracoSocialMediaService(model.Content),
                                                                   null, null);

            // Redirect non-preferred URL - these are sent out in job alerts until May 2018, and linked from the TalentLink back office
            if (!String.IsNullOrEmpty(Request.QueryString["nPostingTargetID"]))
            {
                var jobsProvider = new JobsDataFromApi(new Uri(ConfigurationManager.AppSettings["JobsApiBaseUrl"]), viewModel.JobsSet, new Uri(model.Content.UrlAbsolute()), new HttpClientProvider(), new MemoryJobCacheStrategy(MemoryCache.Default, Request.QueryString["ForceCacheRefresh"] == "1"));
                viewModel.Job = await jobsProvider.ReadJob(Request.QueryString["nPostingTargetID"]);

                if (viewModel.Job.Id > 0)
                {
                    return(new RedirectResult(viewModel.Job.Url.ToString(), true));
                }
            }
            else
            {
                // Show page for preferred URL
                var jobUrlSegment = Regex.Match(Request.Url.AbsolutePath, "/([0-9]+)/");
                if (jobUrlSegment.Success)
                {
                    var jobsProvider = new JobsDataFromApi(new Uri(ConfigurationManager.AppSettings["JobsApiBaseUrl"]), viewModel.JobsSet, new Uri(model.Content.UrlAbsolute()), new HttpClientProvider(), new MemoryJobCacheStrategy(MemoryCache.Default, Request.QueryString["ForceCacheRefresh"] == "1"));
                    viewModel.Job = await jobsProvider.ReadJob(jobUrlSegment.Groups[1].Value);

                    if (viewModel.Job.Id == 0 || viewModel.Job.ClosingDate < DateTime.Today)
                    {
                        // The job URL looks valid but the job isn't in the index, so it's probably closed.
                        // Find some similar jobs to suggest the user may want to apply for instead.
                        await FindSimilarJobs(jobsProvider, viewModel);
                    }
                }
                else
                {
                    // The page was accessed by its default Umbraco URL with no parameters. Returning HttpNotFoundResult() ends up with a generic browser 404,
                    // so to get our custom one we need to look it up and transfer control to it.

                    // However, we need to check for "alttemplate" because a link from a TalentLink job alert or the TalentLink back office to an expired job
                    // is a link to the default Umbraco URL with just a querystring that doesn't match any data. That in turn will want to load the jobs CSS for
                    // a job that matches nothing, and that request ends up here. We want it to continue and return the JobsCss view, not our 404 page.
                    if (String.IsNullOrEmpty(Request.QueryString["alttemplate"]))
                    {
                        var notFoundUrl = new HttpStatusFromConfiguration().GetCustomUrlForStatusCode(404);
                        if (notFoundUrl != null && Server != null)
                        {
                            Server.TransferRequest(notFoundUrl + "?404;" + HttpUtility.UrlEncode(Request.Url.ToString()));
                        }
                    }
                }
            }

            // The page should expire when the job closes
            var expirySeconds = 86400; // one day

            if (viewModel.Job != null && viewModel.Job.ClosingDate != null)
            {
                var secondsToClosingDate = (int)(viewModel.Job.ClosingDate.Value.AddDays(1).Date.ToUkDateTime() - DateTime.Now.ToUkDateTime()).TotalSeconds;
                if (secondsToClosingDate >= 0)
                {
                    expirySeconds = secondsToClosingDate;
                }
            }
            new HttpCachingService().SetHttpCacheHeadersFromUmbracoContent(model.Content, UmbracoContext.Current.InPreviewMode, Response.Cache, new IExpiryDateSource[] { expiryDate, new ExpiryDateFromPropertyValue(model.Content, "latestUnpublishDate_Latest") }, expirySeconds);

            return(CurrentTemplate(viewModel));
        }
 public override ActionResult Index(RenderModel model)
 {
     return(base.Index(model));
 }
Exemple #17
0
 public override ActionResult Index(RenderModel model)
 {
     return(CurrentTemplate(BuildModel <ViewModelBase>()));
 }
        public void RendererViewText()
        {
            // setup environment for unit testing

            RunContext.IsTesting    = true;
            RunContext.RuntimeCache = new TestRuntimeCacheProvider();

            // setup MVC

            var controller = new TestBlocksController();

            var controllerContextMock = new Mock <ControllerContext>();

            controllerContextMock.Setup(c => c.Controller).Returns(controller);
            var controllerContext = controllerContextMock.Object;

            var engineMock = new Mock <IViewEngine>();
            var engine     = engineMock.Object;

            engineMock.Setup(e => e.FindView(It.IsAny <ControllerContext>(), "main", null, It.IsAny <bool>()))
            .Returns(new ViewEngineResult(new MainView(), engine));
            engineMock.Setup(e => e.FindPartialView(It.IsAny <ControllerContext>(), "block1", It.IsAny <bool>()))
            .Returns(new ViewEngineResult(new Block1View(), engine));
            engineMock.Setup(e => e.FindPartialView(It.IsAny <ControllerContext>(), "block2", It.IsAny <bool>()))
            .Returns(new ViewEngineResult(new Block2View(), engine));

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(engine);

            // setup blocks

            BlocksController.Settings.CacheProfiles["forever"] = new CacheProfile
            {
                Mode     = "cache",
                Duration = 6666666
            };

            BlocksController.Settings.CacheMode["cache"] = (xBlock, xContent, xViewData) => CacheMode.Cache;

            BlocksController.Settings.MergeMeta = (blockModel, objects) =>
            {
                if (objects == null)
                {
                    return;
                }
                var list = (List <string>)objects["test"];
                if (!blockModel.Meta.ContainsKey("test"))
                {
                    blockModel.Meta["test"] = new List <string>();
                }
                ((List <string>)blockModel.Meta["test"]).AddRange(list);
            };

            // test

            const string json = @"
[
    {
        ""Source"": ""main"",
        ""Blocks"": [
            {
                ""Source"": ""Block1""
            },
            {
                ""Source"": ""Block2"",
                ""Cache"": ""forever""
            }
        ]
    }
]
";

            var content = new PublishedContent
            {
                Structures = JsonSerializer.Instance.Deserialize <StructureDataValue[]>(json)
            };
            var model = new RenderModel(content, CultureInfo.CurrentUICulture);

            var rs = RenderingStructure.Compute(null, content, x => ((PublishedContent)x).Structures);

            Assert.IsNotNull(rs);

            var cacheMode = rs.Cache == null
                ? CacheMode.Ignore
                : rs.Cache.GetCacheMode(rs, model.Content, null);

            var text = cacheMode == CacheMode.Ignore
                ? Renderer.ViewText(controllerContext, rs, model.Content, model.CurrentCulture)
                : Renderer.ViewTextWithCache(controllerContext, rs, model.Content, model.CurrentCulture, cacheMode == CacheMode.Refresh);

            Console.WriteLine(text);

            text = cacheMode == CacheMode.Ignore
                ? Renderer.ViewText(controllerContext, rs, model.Content, model.CurrentCulture)
                : Renderer.ViewTextWithCache(controllerContext, rs, model.Content, model.CurrentCulture, cacheMode == CacheMode.Refresh);

            Console.WriteLine(text);

            // expected:
            //main
            //block1 635640043255160266
            //block2 635640043255520520
            //meta: block1,block2
            //main
            //block1 635640043255580629 <<<< different
            //block2 635640043255520520 <<<< identical to previous one
            //meta: block1,block2
        }
 public RenderModelComponent(string name, RenderModel model)
 {
     this.name  = name;
     this.model = model;
 }
 public ActionResult HomePage(RenderModel model)
 {
     return(View());
 }
Exemple #21
0
        /// <inheritdoc />
        public override ActionResult Index(RenderModel model)
        {
            var m = model.Content.ToModel <EventCodePageModel>().LoginPage;

            return(View("~/Views/Login.cshtml", m));
        }
		/// <summary>
		/// Convierte los argumentos proporcionados en la plantilla al tipo que recibe la función.
		/// </summary>
		static object[] ConvertFuncParameters(string name,
			MethodInfo function, 
			List<string> templateArguments,
			RenderModel model, 
			RenderContext context)
		{
			var funcParameters = function.GetParameters();
			var convertedValues = new object[funcParameters.Length];

			if(funcParameters.Length > 0)
			{				
				var lastIndex = funcParameters.Length - 1;
				var last = funcParameters[lastIndex];

				if(templateArguments.Count > funcParameters.Length && 
				   last.ParameterType != typeof(string[]))
				{
					throw new TemplateException(string.Format(
						"The function {0} is expecting {1} parameters and receives {2}", 
						name, funcParameters.Length, templateArguments.Count));
				}

				// si la función tiene un argumento más solo puede ser un tipo especial:
				// o rendercontext o string[] que es como un params en c#
				if(templateArguments.Count == funcParameters.Length - 1)
				{
					if(last.ParameterType == typeof(string[]))
					{
						convertedValues[lastIndex] = new string[0];
					}
					else if(last.ParameterType != typeof(RenderContext))
					{
						throw new TemplateException(string.Format(
							"The function {0} is expecting {1} parameters and receives {2}", 
							name, funcParameters.Length, templateArguments.Count));
					}
				}

				if(last.ParameterType == typeof(RenderContext))
				{
					convertedValues[lastIndex] = context;
				}
				// esto es como un params string[]
				else if(last.ParameterType == typeof(string[]))
				{
					convertedValues[lastIndex] = templateArguments.Skip(lastIndex).Select(
						t => ConvertToString(context,t)).ToArray();
				}	
			}

			// convertir todos los parámetros
			for(int i = 0, l = templateArguments.Count; i < l; i++)
			{
				if(convertedValues[i] != null)
				{
					break; // ya se ha llegado a un param especial (RenderContext o string[])
				}

				var argument = templateArguments[i];

				// si empieza por . es que es un valor del modelo.
				var value = argument[0] == '.' ? Template.GetValue(context.RenderModel, argument) : argument;

				try
				{
					if(value != null && funcParameters[i].ParameterType != typeof(object))
					{
						convertedValues[i] = Convert.ChangeType(value, funcParameters[i].ParameterType);
					}
					else
					{
						convertedValues[i] = value;
					}
				}
				catch(Exception ex)
				{
					throw new TemplateException(string.Format(
						"Error converting parameter {0} in {1}: {2}",  i, function.Name, ex.Message));
				}
			}

			return convertedValues;
		}
        /// <summary>
        /// Used to render the search result listing (virtual node)
        /// </summary>
        /// <param name="model"></param>
        /// <param name="term">
        /// The search term
        /// </param>
        /// <param name="provider">
        /// The search provider name (optional)
        /// </param>
        /// <param name="p"></param>
        /// <returns></returns>
        public ActionResult Search(RenderModel model, string term, string provider = null, int?p = null)
        {
            var tagPage = model.Content as ArticulateVirtualPage;

            if (tagPage == null)
            {
                throw new InvalidOperationException("The RenderModel.Content instance must be of type " + typeof(ArticulateVirtualPage));
            }

            //create a blog model of the main page
            var rootPageModel = new ListModel(model.Content.Parent);

            if (term == null)
            {
                //nothing to search, just render the view
                var emptyList = new ListModel(tagPage, Enumerable.Empty <IPublishedContent>(), new PagerModel(rootPageModel.PageSize, 0, 0));
                return(View(PathHelper.GetThemeViewPath(emptyList, "List"), emptyList));
            }

            if (p == null || p.Value <= 0)
            {
                p = 1;
            }



            var splitSearch = term.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var fields      = new Dictionary <string, int>
            {
                { "markdown", 2 },
                { "richText", 2 },
                { "nodeName", 3 },
                { "tags", 1 },
                { "categories", 1 },
                { "umbracoUrlName", 3 }
            };
            var fieldQuery = new StringBuilder();

            //build field query
            foreach (var field in fields)
            {
                //full exact match (which has a higher boost)
                fieldQuery.Append(string.Format("{0}:{1}^{2}", field.Key, "\"" + term + "\"", field.Value * 3));
                fieldQuery.Append(" ");
                //NOTE: Phrase match wildcard isn't really supported unless you use the Lucene
                // API like ComplexPhraseWildcardSomethingOrOther...
                //split match
                foreach (var s in splitSearch)
                {
                    //match on each term, no wildcard, higher boost
                    fieldQuery.Append(string.Format("{0}:{1}^{2}", field.Key, s, field.Value * 2));
                    fieldQuery.Append(" ");

                    //match on each term, with wildcard
                    fieldQuery.Append(string.Format("{0}:{1}*", field.Key, s));
                    fieldQuery.Append(" ");
                }
            }

            var criteria = provider == null
                ? ExamineManager.Instance.CreateSearchCriteria()
                : ExamineManager.Instance.SearchProviderCollection[provider].CreateSearchCriteria();

            criteria.RawQuery(string.Format("+parentID:{0} +({1})", rootPageModel.BlogArchiveNode.Id, fieldQuery));

            var searchProvider = provider == null
                ? ExamineManager.Instance.DefaultSearchProvider
                : ExamineManager.Instance.SearchProviderCollection[provider];

            var searchResult = Umbraco.TypedSearch(criteria, searchProvider).ToArray();

            //TODO: I wonder about the performance of this - when we end up with thousands of blog posts,
            // this will probably not be so efficient. I wonder if using an XPath lookup for batches of children
            // would work? The children count could be cached. I'd rather not put blog posts under 'month' nodes
            // just for the sake of performance. Hrm.... Examine possibly too.

            var totalPosts = searchResult.Count();
            var pageSize   = rootPageModel.PageSize;

            var totalPages = totalPosts == 0 ? 1 : Convert.ToInt32(Math.Ceiling((double)totalPosts / pageSize));

            //Invalid page, redirect without pages
            if (totalPages < p)
            {
                return(new RedirectToUmbracoPageResult(model.Content.Parent, UmbracoContext));
            }

            var pager = new PagerModel(
                pageSize,
                p.Value - 1,
                totalPages,
                totalPages > p ? model.Content.Url.EnsureEndsWith('/') + term + "/" + (p + 1) : null,
                p > 1 ? model.Content.Url.EnsureEndsWith('/') + term + "/" + (p - 1) : null);

            var listModel = new ListModel(tagPage, searchResult, pager);

            return(View(PathHelper.GetThemeViewPath(listModel, "List"), listModel));
        }
Exemple #24
0
 public override ActionResult Index(RenderModel model)
 {
     return(CurrentTemplate(new ContactViewModel(model.Content as Contact)));
 }
 /// <summary>
 /// Gets the view model
 /// </summary>
 /// <param name="render">The RenderModel for the request</param>
 protected abstract TviewModel GetViewModel(RenderModel render);