adoconnection / RazorEngineCore

.NET6 Razor Template Engine
MIT License
565 stars 84 forks source link

List<T> cast error #91

Closed jddj007-hydra closed 2 years ago

jddj007-hydra commented 2 years ago

when i try to user a List<KeyValuePair<string,string>> or a Dictionary<string,string> like this: ` @foreach (var item in Model.Languages){

} ` got this error:

Unable to cast object of type 'System.Collections.Generic.List1[System.Collections.Generic.KeyValuePair2[System.String,System.String]]' to type 'System.Collections.Generic.IEnumerable`1[System.Object]'.

error stackTrace is at System.Runtime.CompilerServices.CastHelpers.ChkCastAny(Void* toTypeHnd, Object obj) at RazorEngineCore.AnonymousTypeWrapper.TryGetMember(GetMemberBinder binder, Object& result) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at TemplateNamespace.Template.d0.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at RazorEngineCore.RazorEngineCompiledTemplate.d12.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at RazorEngineCore.RazorEngineCompiledTemplate.Run(Object model)

i upgrade to dotnet6 ,before this update ,this code runs very well. then i change model to Languages = list.Select(v=>(object)v).ToList(); it works!!

hope to fix this issue.

jddj007-hydra commented 2 years ago

i changed AnonymousTypeWrapper.cs modify TryGetMember method `

        if (isEnumerable && !(result is string))
        {
            result = result as IEnumerable;
            //((IEnumerable<object>) result)
            //        .Select(e =>
            //        {
            //            if (e.IsAnonymous())
            //            {
            //                return new AnonymousTypeWrapper(e);
            //            }

            //            return e;
            //        })
            //        .ToList();
        }

` when i use List or Dictionary<TKey,TValue> looks like ok, plz fix it .

adoconnection commented 2 years ago

thanks!

adoconnection commented 2 years ago

Install-Package RazorEngineCore -Version 2022.1.1 new package released