dotnet-practitioner
dotnet-practitioner

Reputation: 14148

IList type cast question

I got this line of code from a book. I don't understand how would some one know that controller.List().ViewData.Model could be typecasted as IList??

var people = controller.List().ViewData.Model as IList<Person>;

Upvotes: 2

Views: 286

Answers (2)

Samuel Neff
Samuel Neff

Reputation: 74909

What you have is a call to an ASP.NET MVC controller but instead of using this to render a view, you're accessing the ViewData directly.

Typically in ASP.NET MVC you'll create a typed view for your views which will inherit from System.Web.Mvc.ViewPage<T> and in this case it would be System.Web.Mvc.ViewPage<IList<Person>>. Once you've created this typed view, within the view you know that ViewData.Model is of type IList<Person>.

Calls like the one you posted are commonly used in unit testing the controllers. In this case you directly call the controller method and get back the ViewResult which has the data inside it. When writing the unit test, you know that ViewData.Model is of type IList<Person> 'cause that's the contract--that's what the unit test is for, to verify that the controller generated a model of the right type and has the right data.

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82345

You would have to know the object model, in most cases you are familiar with the framework you are using and the IDE offers many helpful tools to assist with object investigation.

Upvotes: 1

Related Questions