// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using Microsoft.AspNet.Razor.Chunks; namespace Microsoft.AspNet.Mvc.Razor.Directives { /// /// Contains helper methods for dealing with Chunks /// public static class ChunkHelper { /// /// Token that is replaced by the model name in @inherits and @inject /// chunks as part of . /// public static readonly string TModelToken = "TModel"; private static readonly string TModelReplaceToken = $"<{TModelToken}>"; /// /// Returns the used to determine the model name for the page generated /// using the specified /// /// The to scan for s in. /// The last in the if found, null otherwise. /// public static ModelChunk GetModelChunk(ChunkTree chunkTree) { if (chunkTree == null) { throw new ArgumentNullException(nameof(chunkTree)); } // If there's more than 1 model chunk there will be a Razor error BUT we want intellisense to show up on // the current model chunk that the user is typing. return chunkTree .Chunks .OfType() .LastOrDefault(); } /// /// Returns the type name of the Model specified via a in the /// if specified or the default model type. /// /// The to scan for s in. /// The name of the default model. /// The model type name for the generated page. public static string GetModelTypeName( ChunkTree chunkTree, string defaultModelName) { if (chunkTree == null) { throw new ArgumentNullException(nameof(chunkTree)); } if (defaultModelName == null) { throw new ArgumentNullException(nameof(defaultModelName)); } var modelChunk = GetModelChunk(chunkTree); return modelChunk != null ? modelChunk.ModelType : defaultModelName; } /// /// Returns a string with the <TModel> token replaced with the value specified in /// . /// /// The string to replace the token in. /// The model name to replace with. /// A string with the token replaced. public static string ReplaceTModel( string value, string modelName) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (modelName == null) { throw new ArgumentNullException(nameof(modelName)); } return value.Replace(TModelReplaceToken, modelName); } } }