0

I have a ViewModel and a ReadOnly Property in that view model that I can't seem to access in the view.

Public ReadOnly Property ListOfSubjects() As List(Of ListOfSubjects)
    Get
        Return FeedbackSubjectsContract.GetList()
    End Get
End Property

The problem is that in my view when I attempt to loop through the "ListOfSubjects" I am getting "Object reference not set to instance of the object"

The Controller looks like this

Function Index() As ActionResult
   Return View()
End Function

The View looks like this:

<%
   For Each myItem In Model.ListOfSubjects
     Response.Write(myItem.SubjectName))
   Next
%>

Also, the view is strongly typed and inherits the correct Model. Actually, I can set that property in the controller okay and return a newly-initialized model to my view and that works okay but I can't seem to set the value of that list in my model (which is where I would like to do it)

What am I doing wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
Solo812
  • 401
  • 1
  • 8
  • 19

2 Answers2

0

I'm a C# guy but assuming VB View() function is the same, you are not passing a view model to the view:

Return View(/*should be passing a view model here*/)

Notice in this article, they are passing data Return View(db.Movies.ToList())

http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/vb/accessing-your-model%27s-data-from-a-controller

There is a Previous link at the bottom of the article that will take you back to the page where they are creating the model.

AaronLS
  • 37,329
  • 20
  • 143
  • 202
  • Since the view is strongly typed shouldn't it inherit that read only property and allow me to access the list(Of ListOfSubjects)? – Solo812 Dec 04 '13 at 21:30
  • You're confusing an instance of a type with the type. The type of the model is the structure of the data, but you have to create an instance of that type in your controller, populate it with data, and then pass it to the View. The strongly typed View just indicates what type is valid to pass to `Return View(someModel)` – AaronLS Dec 04 '13 at 23:34
0

Thank you AaronLS. I did assume that the "model" was more like an instance of a class being passed into the controller. I was able to resolve the problem by creating a "New" Model, setting the properties, and then passing it into the return statement.

Thanks all!

Solo812
  • 401
  • 1
  • 8
  • 19