I have a simple class that includes 2 properties, one String and one a List of generic Objects. It looks like this:
public class SessionFieldViewModel
{
private String _name;
public String Name
{
get { return _name; }
set { _name = valu开发者_开发知识库e; }
}
private List<Object> _value;
public List<Object> Value
{
get { return _value ?? new List<Object>(); }
set { _value = value; }
}
}
Within my main code (MVC Controller) I am trying to manually populate this class. Keep in mind that when I pass data from a webform into this class using the default model binder this get populated just fine.
When Manually trying to create a record and and add it to a list I do this:
Guid id = Guid.NewGuid();
var _searchField = new SessionFieldViewModel();
_searchField.Name = "IDGUID";
Object _object = (Object)id;
_searchField.Value.Add(_object);
_searchFields.Fields.Add(_searchField);
When I do this I do get a populated class with a Name property of "IDGUID", but the generic lists of objects comes back null.
When I debug the code and walk it though the data seems to all be there and working as I am doing it, but when I get through and inspect _searchFields it does not show anything in the Value property of Fields.
Ideas?
Thanks in advance.
Tom tlatourelle
It appears you never set _value
when it is null from the getter. Try
public List<Object> Value
{
get { return _value ?? (_value = new List<Object>()); }
set { _value = value; }
}
_value
is never getting set to an instance of List<Object>
; it is always null. What's happening is you are returning a new List<Object>
and adding an Object
to it, but you're immediately discarding the newly-created List<Object>
.
You need to change your definition of Value
to something like this:
private List<Object> _value = new List<Object>();
public List<Object> Value
{
get { return _value; }
set { _value = value; }
}
精彩评论