c# - 为什么我在尝试呈现此 .NET 视图时会获得此“InvalidOperationException”?
问题描述
我是.NET和C#的新手(我来自 Java 和 Spring 框架),我在学习教程时遇到了一些问题。
我有这个简单的控制器类:
namespace Vidly.Controllers
{
public class CustomersController : Controller
{
public ViewResult Index()
{
var customers = GetCustomers();
return View(customers);
}
public ActionResult Details(int id)
{
System.Diagnostics.Debug.WriteLine("Into Details()");
var customer = GetCustomers().SingleOrDefault(c => c.Id == id);
System.Diagnostics.Debug.WriteLine("customer: " + customer.Id + " " + customer.Name);
if (customer == null)
return HttpNotFound();
return View(customer);
}
private IEnumerable<Customer> GetCustomers()
{
return new List<Customer>
{
new Customer { Id = 1, Name = "John Smith" },
new Customer { Id = 2, Name = "Mary Williams" }
};
}
}
}
如您所见,此类包含此Details(int id)方法:
public ActionResult Details(int id)
{
System.Diagnostics.Debug.WriteLine("Into Details()");
var customer = GetCustomers().SingleOrDefault(c => c.Id == id);
System.Diagnostics.Debug.WriteLine("customer: " + customer.Id + " " + customer.Name);
if (customer == null)
return HttpNotFound();
return View(customer);
}
因此,此方法处理针对 URL的GET类型的HTTP请求,例如:
localhost:62144/Customers/Details/1
它似乎有效,因为在输出控制台中我获得了Into Details()日志。另一个日志还解释了客户模型对象已正确初始化,事实上我获得了这个控制台输出:
customer: 1 John Smith
然后控制器返回一个包含前一个模型对象的ViewResult对象(调用View方法)。
我认为 .NET 会自动尝试将此ViewResult对象(包含模型)发送到与处理此请求的控制器方法具有相同名称的视图。所以我有这个Details.cshtml视图:
@model Vidly.Models.Customer
@{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@Model.Name</h2>
理论上应该接收这个ViewResult对象,从这里提取模型对象(具有Vidly.Models.Customer作为类型),它应该打印这个模型对象的Name属性的值。
问题是我得到了这个异常,而不是带有预期数据的预期页面:
[InvalidOperationException: The model item passed into the dictionary is of type 'Vidly.Models.Customer', but this dictionary requires a model item of type 'Vidly.ViewModels.RandomMovieViewModel'.]
为什么?这是什么意思?
Vidly.ViewModels.RandomMovieViewModel 是另一个模型对象,用于另一个控制器和另一个视图。
问题是什么?我错过了什么?我该如何解决这个问题?
解决方案
由于文件中的Vidly.ViewModels.RandomMovieViewModel模型声明而出现此错误_Layout.cshtml
。
在布局视图中声明模型意味着所有使用布局视图的视图必须使用该模型类或派生自该布局视图模型类的类
推荐阅读
- python - pip install pyinstaller 失败,显示 SSL 错误
- python-3.x - 如何修复可用于 CVGridsearch 的 loky 进程
- php - 如何在谷歌表格 API 上使用过滤器在 ASC 中显示数据值?
- github - 不使用移动设备的 VPN 或热点无法访问 GitHub
- rust - 为拥有的奶牛重用向量堆空间而不转换?
- system - 从命令行状态(200)ok和浏览器状态(404)未找到,浏览器无法找到数据的原因是什么?
- visual-studio-code - 文本的字体连字
- apache-kafka - 卡夫卡消费者表现出滞后
- javascript - 奇怪的解构赋值,给出未定义
- angular - 如何从 Firebase 检索对象的 id 并存储每个对象?