我在.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);
}
因此,此方法处理GET类型的HTTP请求朝向 URL,如下所示:
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
文件中的模型声明而出现此错误。
在布局视图中声明模型意味着使用布局视图的所有视图都必须使用该模型类或派生自该布局视图模型
类的类