请允许我在前言中说其他SO问题没有回答我的问题。
我是ASP.net的新手,我正在关注一些在线教程。现在,我在传递模型时遇到了问题。错误是:
传递到字典中的模型项的类型为“Vidly.ViewModels.DetailCustomersViewModel”,但此字典需要“Vidly.ViewModels.RandomMovieViewModel”类型的模型项。
然而,这对我没有意义,因为我不记得设置任何字典。以下代码适用于我的电影页面。
视图模型:
namespace Vidly.ViewModels
{
public class RandomMovieViewModel
{
public Movie Movie { get; set; }
public List<Customer> Customers { get; set; }
}
}
控制器:
namespace Vidly.Controllers
{
public class MoviesController : Controller
{
// GET: Movies/random
public ActionResult Random()
{
var movie = new Movie() { Name = "Shrek!" };
var customers = new List<Customer>
{
new Customer { Name = "Michael"},
new Customer { Name = "SlowPC"}
};
var movieModel = new RandomMovieViewModel
{
Movie = movie,
Customers = customers
};
return View(movieModel);
//return Content("Hello World");
//return HttpNotFound();
//return new EmptyResult();
//return RedirectToAction("Index", "Home", new { page = 1, sortBy = "name" });
}
}
在我们的CSHTML中,我们将其称为:
@model Vidly.ViewModels.RandomMovieViewModel
@{
ViewBag.Title = "Random";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
var className = Model.Customers.Count > 5 ? "popular" : null;
}
然而,当我为我的DetailsCustomer做同样的事情时,它会抛出错误,我不知道为什么
视图模型:
namespace Vidly.ViewModels
{
public class DetailCustomersViewModel
{
public List<Customer> Customers { get; set; }
}
}
控制器:
namespace Vidly.Controllers
{
public class CustomersController : Controller
{
[Route("customers/details/{Id}")]
public ActionResult Details(int? Id)
{
var customers = new List<Customer>
{
new Customer { Id = 1, Name = "Jane Doe"},
new Customer { Id = 2, Name = "John Smith"}
};
var customersModel = new DetailCustomersViewModel
{
Customers = customers
};
return View(customersModel);
}
}
CSHTML:
@model Vidly.ViewModels.DetailCustomersViewModel
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
var className = Model.Customers.Count > 5 ? "popular" : null;
}
<h2 class="@className">Customers</h2>
正如你可以想象的那样,当我真正传递正确的类型时,我对于如何存在类型不匹配感到十分困惑;而且我没有回忆过修改字典。