Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate Route Parameters for View Fetch #4

Merged
merged 10 commits into from
Apr 12, 2018
39 changes: 35 additions & 4 deletions src/Giraffe.Razor/RazorEngine.fs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,51 @@ module RazorEngine =
open FSharp.Control.Tasks.ContextInsensitive
open Giraffe

let private extractRouteData (path:string) =

let templatePath = path + "" //Normalize nulls

//Split path into segments and reverse the orders
let segments =
templatePath.Split('/', '\\')
|> List.ofSeq
|> List.rev

let routeValues =
seq {
for i in 1..segments.Length do
match i with
| 1 -> yield "action", segments.[0]
| 2 -> yield "controller", segments.[1]
| 3 -> yield "area", segments.[2]
| x -> yield sprintf "token-%d" (x), segments.[x - 1]
}

//Create RouteData Object using Values Created
let routeData = RouteData()

for (key,value) in routeValues do
routeData.Values.Add(key, value)

routeData

let renderView (razorViewEngine : IRazorViewEngine)
(tempDataProvider : ITempDataProvider)
(httpContext : HttpContext)
(viewName : string)
(model : 'T) =
task {
let actionContext = ActionContext(httpContext, RouteData(), ActionDescriptor())
let viewEngineResult = razorViewEngine.FindView(actionContext, viewName, true)
let routeData = extractRouteData(viewName)
let templateName = routeData.Values.["action"].ToString()

let actionContext = ActionContext(httpContext, routeData, ActionDescriptor())
let viewEngineResult = razorViewEngine.FindView(actionContext, templateName, true)

match viewEngineResult.Success with
| false ->
let locations = String.Join(" ", viewEngineResult.SearchedLocations)
return Error (sprintf "Could not find view with the name '%s'. Looked in %s." viewName locations)
| true ->
return Error (sprintf "Could not find view with the name '%s'. Looked in %s." templateName locations)
| true ->
let view = viewEngineResult.View
let viewDataDict = ViewDataDictionary<'T>(EmptyModelMetadataProvider(), ModelStateDictionary(), Model = model)
let tempDataDict = TempDataDictionary(actionContext.HttpContext, tempDataProvider)
Expand Down