简体   繁体   English

在视图中提取 ViewBag 动态数据:RuntimeBinderException:“对象”不包含“名称”的定义

[英]Extract ViewBag Dynamic Data in View : RuntimeBinderException: 'object' does not contain a definition for 'Name'

I am getting a dynamic model like this-我得到一个像这样的动态 model -

var termDetail = await _context.Terms
                .Include(t => t.Parents).ThenInclude(p => p.Parent)
                .Include(t => t.Children).ThenInclude(c => c.Child)
                .Select(term => new
                {
                    Id = term.Id,
                    Name = term.Name,
                    ParentCount = term.Parents.Count(),
                    ChildCount = term.Children.Count(),
                    Parents = term.Parents.Select(p => new
                    {
                        Id = p.Parent.Id,
                        Name = p.Parent.Name,
                        ParentCount = p.Parent.Parents.Count(),
                        ChildCount = p.Parent.Children.Count()
                    }),
                    Children = term.Children.Select(c => new
                    {
                        Id = c.Child.Id,
                        Name = c.Child.Name,
                        ParentCount = c.Child.Parents.Count(),
                        ChildCount = c.Child.Children.Count()
                    })
                })
                .FirstOrDefaultAsync(m => m.Id == id);

I am passing it to view like this-我将它传递给这样查看-

(In Controller) (在控制器中)

ViewBag.term = termDetail;

(In View) (在视图中)

<dd>
    ....
    ....
    @ViewBag.term.Name
</dd>

If I debug, I am getting this-如果我调试,我会得到这个-

调试

So, the value is actually passed from controller to view.因此,该值实际上是从 controller 传递给查看的。

But I can't show it in view.但我无法在视图中显示它。 I am getting this error-我收到这个错误-

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。 RuntimeBinderException: 'object' does not contain a definition for 'Name' RuntimeBinderException:“对象”不包含“名称”的定义

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Name'
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at AspNetCore.Views_Terms_Details.ExecuteAsync() in D:\Education\0. Research\1. Knowledge-Base\Code\Asp.NetCore_3.1-PostGRE_Role-Claim_Management\Views\Terms\Details.cshtml:line 21
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
   at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at WebMarkupMin.AspNetCore3.WebMarkupMinMiddleware.ProcessAsync(HttpContext context, Boolean useMinification, Boolean useCompression)
   at WebMarkupMin.AspNetCore3.WebMarkupMinMiddleware.ProcessAsync(HttpContext context, Boolean useMinification, Boolean useCompression)
   at WebMarkupMin.AspNetCore3.WebMarkupMinMiddlewareBase.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

在此处输入图像描述

I like to do it without creating a View Model .我喜欢在不创建视图 Model的情况下这样做。

Is it possible?可能吗?

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。 RuntimeBinderException: 'object' does not contain a definition for 'Name' RuntimeBinderException:“对象”不包含“名称”的定义

You can try to implement and use the following extension method "ToExpando" to convert your anonymous-types data.您可以尝试实现并使用以下扩展方法“ToExpando”来转换您的匿名类型数据。

public static class MyExtensions
{
    public static ExpandoObject ToExpando(this object anonymousObject)
    {
        IDictionary<string, object> expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(anonymousObject.GetType()))
        {
            expando.Add(property.Name, property.GetValue(anonymousObject));
        }

        return (ExpandoObject)expando;
    }
}

In controller在 controller

ViewBag.term = termDetail.ToExpando();

Test Result测试结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Viewbag RuntimeBinderException:“对象”不包含定义 - Viewbag RuntimeBinderException: 'object' does not contain a definition ViewBag RuntimeBinderException:“对象”不包含“ProfileId”的定义 - ViewBag RuntimeBinderException: 'object' does not contain a definition for 'ProfileId' RuntimeBinderException:“对象”不包含“名称”的定义 - RuntimeBinderException: 'object' does not contain a definition for 'Name' 对象”不包含动态数据MainTypeCode的定义 - object' does not contain a definition for MainTypeCode for dynamic data RuntimeBinderException:&#39;IReadDataService&#39;不包含&#39;GetBySlug&#39;的定义 - RuntimeBinderException: 'IReadDataService ' does not contain a definition for 'GetBySlug' 'object'不包含动态定义 - 'object' does not contain a definition for dynamic &#39;object&#39;不包含&#39;Name&#39;的定义 - 'object' does not contain a definition for 'Name' “对象”不包含“名称”的定义 - “Object” does not contain a definition for “name” “对象”不包含“名称”的定义 - “object” does not contain a definition for 'Name' LINQ加入Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:&#39;对象&#39;不包含以下内容的定义: - LINQ Join Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM