3

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 = value; }
    }

    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

1
  • Where does the generic list comes null? A model binder is used for binding values coming from an HTTP request. How does your view look like? What about the POST action? Why are you using List<object>? Why generics when you don't know the type at compile time? Seems kinda useless. Commented May 11, 2011 at 22:02

2 Answers 2

4

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good catch. I didn't see that. Also since this code is also working through the Default Model Binder and returning actual values in another use case I didn't consider that this part would be broken.
2

_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; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.