简体   繁体   中英

Adding item to the List<T>

I am probably doing something silly but cannot find out what. I am trying to modify simple membership functionality in ASP.NET MVC 4. I have slightly modified a RegisterModel coming with the template, and added a list of categories to it like so:

public class RegisterModel
{
    ...

    public List<SelectListItem> Categories { get; set; }
}

Then in the account controller I'm trying to add an item to this list but get " Object reference not set to an instance of an object. " error:

[AllowAnonymous]
public ActionResult Register()
{
    RegisterModel rm = new RegisterModel();

    //SelectListItem guestCategory = new SelectListItem();
    //guestCategory.Value = null;
    //guestCategory.Text = "Guest";

    rm.Categories.Add(new SelectListItem { Value = null, Text = "Guest" });
...

Any ideas why?

you just need to do this before adding items to list , because when you add items its not get instantiated that why its giving error

rm.Categories = new List<SelectListItem>();

that means in this method do like this

[AllowAnonymous]
public ActionResult Register()
{
    RegisterModel rm = new RegisterModel();

    rm.Categories = new List<SelectListItem>();//added line 

    rm.Categories.Add(new SelectListItem { Value = null, Text = "Guest" });
...

or

you can do same thing in constructor of RegisterModel .

public class RegisterModel
{
  public RegisterModel
  {
    Categories = new List<SelectListItem>();//added line 
  }  

In your class constructor initialize the list

public class RegisterModel
{
    RegisterModel()
    {
     Categories  = new List<SelectListItem>();
    }
......

Since you are using an auto-implemented property {get;set;} you have to initialize it in the constructor. If you don't want to do in the Constructor then you can do:

public class RegisterModel
{
    ...
    private List<SelectListItem> _Categories = new List<SelectListItem>();

    private List<SelectListItem> Categories
    {
        get { return _Categories; }
        set { _Categories = value; }
    }
}

You can also initialize the List with the object, before using it.

RegisterModel rm = new RegisterModel();
r.Categories = new List<SelectListItem>(); // like that
rm.Categories.Add(new SelectListItem { Value = null, Text = "Guest" });

But its better if you initialize the list in constructor or through a private field (if not using auto-implemented property) , Because then you don't have to initialize a property of the object of Class RegisterModel , with each object creation.

You never initialized Categories to anything. It is null .

Initialize it to an empty list to avoid the error, preferably in the constructor:

Categories = new List<SelectListItem>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM