首页 > 解决方案 > 为什么我在尝试呈现此 .NET 视图时会获得此“InvalidOperationException”?

问题描述

我是.NETC#的新手(我来自 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 是另一个模型对象,用于另一个控制器和另一个视图。

问题是什么?我错过了什么?我该如何解决这个问题?

标签: c#asp.net.netasp.net-mvc

解决方案


由于文件中的Vidly.ViewModels.RandomMovieViewModel模型声明而出现此错误_Layout.cshtml

在布局视图中声明模型意味着所有使用布局视图的视图必须使用该模型类或派生自该布局视图模型类的类


推荐阅读