I am pretty new in .NET and C# (I came from Java and Spring framework) and I have some problem following a tutorial.
I have this simple controller class:
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" }
};
}
}
}
As you can see this class contains this Details(int id) method:
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);
}
So, this method handle HTTP request of type GET toward URL like:
localhost:62144/Customers/Details/1
and it seems to work because into the output console I obtain the Into Details() log. Also the other log explains that the customer model object is correctly initialized, infact I obtain this console output:
customer: 1 John Smith
Then the controller reuturn a ViewResult object (calling the View method) containinf the previous model object.
I think that .NET automatically try to send this ViewResult object (that contains the model) to a view having the same name of the controller method that handle this request. So I have this Details.cshtml view:
@model Vidly.Models.Customer
@{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@Model.Name</h2>
that in theory should receive this ViewResult object, from here extract the model object (having Vidly.Models.Customer as type) and it should print the value of the Name property of this model object.
The problem is that I am obtaining this excepetion istead the expected page with the expected data:
[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'.]
Why? What it means?
Vidly.ViewModels.RandomMovieViewModel is another model object used into another controller and another view.
What is the problem? What am I missing? How can I fix this issue?