c# - 当部分 View 位于共享文件夹中时,ASP.NET MVC '@model dynamic' 无法识别模型属性

标签 c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

不重复:MVC Razor dynamic model, 'object' does not contain definition for 'PropertyName'

根据那里的答案,

According to David Ebbo, you can't pass an anonymous type into a dynamically-typed view because the anonymous types are compiled as internal. Since the CSHTML view is compiled into a separate assembly, it can't access the anonymous type's properties.

为什么下面的代码 - 据称永远不会工作 - 当部分 View 位于“/Home/_Partial.cshtml”时按我预期的方式工作,但在移动到“/Shared/_Partial.cshtml”时突然停止工作“?

使用 ASP.NET 4.5(和以前的版本),以下生成文本“Hello, World!”到网络浏览器:

~/Controllers/HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TestDynamicModel.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

~/Views/Home/Index.cshtml

@Html.Partial("_Partial", new { Text = "Hello, world!", ShouldRender = true } )

~/Views/Home/_Partial.cshtml

@model dynamic
@if (!Model.ShouldRender)
{
    <p>Nothing to see here!</p>
}
else
{
    <p>@Model.Text</p>
}

但是,当将 _Partial.cshtml 移至 ~/Views/Shared/_Partial.cshtml 时,将在 _Partial.cshtml(第 2 行)中抛出以下错误:

'object' does not contain a definition for 'ShouldRender'

在调试器中检查模型后,我发现了以下属性:

Model { Text = Hello, world!, ShouldRender = True }

最佳答案

虽然问题与 ASP.NET MVC 的行为有关,而且我知道解决方法,但我不确定每个人都知道。这里有一个解决方法,适用于任何只想让自己的代码正常工作的人:Dynamic Anonymous type in Razor causes RuntimeBinderException

关于c# - 当部分 View 位于共享文件夹中时,ASP.NET MVC '@model dynamic' 无法识别模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18986395/

相关文章:

c# - 为什么复选框返回错误值?

javascript - onkeydown ='return (window.event.keyCode doesn' t 允许通过鼠标单击选择输入

c# - 保存 Asp.Net MVC 5 的设置

asp.net - 如何将 ASP.Net Identity User Email 属性引用为外键

c# - 狗以相同的速度前进

c# - System.Security.Cryptography 与 PCLCrypto

javascript - 如何在jquery中的popup中访问Json返回值

c# - 在 net core 中集成测试自定义 HTTP 客户端

asp.net - 我可以在 IIS 5 中自动创建 .NET Web 应用程序/虚拟目录吗?

javascript - 使用 javascript 从 Knockout.Js 读取 Json 数据