不重复: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/