1

I am trying to fill a list of strings but it throws null reference exception.

Code:

public class Validation
{
    public List<string> Errors { get; set; }
}

Class where all validation errors are to be stored:

public object Post(Currency currency)
{
    ClientData clientData = new ClientData();
    if (ModelState.IsValid)
    {
        new CurrencyProvider().Insert(currency);
        clientData.IsValid = true;
        clientData.Data = new CurrencyProvider().GetAll();
    }
    else
    {
        Validation validation = new Validation();
        foreach (var modelState in ModelState)
            foreach (var error in modelState.Value.Errors)
                validation.Errors.Add(error.ErrorMessage);

        clientData.IsValid = false;
        clientData.Data = validation;
    }   

    return clientData;
}

The problem occurs when I fill validation.Errors.Add(error.ErrorMessage). It throws me the null reference exception even though I have done exception handeling globally as follows in my global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalFilters.Filters.Add(new ExceptionFilter());
    }
}

My Exception handler class:

public class ExceptionFilter : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        ViewResult view = new ViewResult();
        view.ViewName = "Error";
        view.ViewBag.Exception = filterContext.Exception.Message;
        filterContext.ExceptionHandled = true;
        filterContext.Result = view;
    }
}

I have my custom Error Handling page but its also not showing, when I debug then I came to know the there is the null reference exception at the time of filling the list of string in:

validation.Errors.Add(error.ErrorMessage)

What am I doing wrong when I fill the List<string> and why is that throwing null reference exception? And why that null reference exception is not coming on to my custom error page?

7
  • 1
    Try replacing your Foreach condtion of Errors with this one:- foreach(ModelError error in modelState.Errors){ ///Your Code } Commented Jan 2, 2016 at 11:29
  • no, still the same issue Commented Jan 2, 2016 at 11:33
  • 1
    Have you remembered to instantiate a new List<string> before doing validation.Errors.Add()? I think the null ref is validation.Errors Commented Jan 2, 2016 at 11:34
  • no hhow do i instantiate it?? Commented Jan 2, 2016 at 11:38
  • geedubb i think u got it!, plz tell me how do i instantiate the list??? Commented Jan 2, 2016 at 11:38

4 Answers 4

2

The issue is that you have not created an instance of List<string> in your Validation class. You can do that by initializing the instance in the class constructor.

public class Validation
{
    public Validation()
    {
         this.Errors = new List<string>();
    }

    public List<string> Errors { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this keyword is not required
0

You need to instantiate a new List<string> before adding to list with validation.Errors.Add().

You could try:

public object Post(Currency currency)
{
    ClientData clientData = new ClientData();
    validation.Errors = new List<string>(); // instantiate
    if (ModelState.IsValid)
    {
        new CurrencyProvider().Insert(currency);
        clientData.IsValid = true;
        clientData.Data = new CurrencyProvider().GetAll();
    }
    else
    {
        Validation validation = new Validation();
        foreach (var modelState in ModelState)
        {
            foreach (var error in modelState.Value.Errors)
            {
                validation.Errors.Add(error.ErrorMessage);
            }
        }
        clientData.IsValid = false;
        clientData.Data = validation;
    }
    return clientData;
}

Comments

0

Try

Validation validation = new Validation();
validation.Errors validationError = new List<string>();

Then write into foreach loop :

validationError.Add(error.ErrorMessage);

Comments

0

What you basically doing is called 'Composition' or 'has a' Relation between classes in object oriented programming ,Composition relation between classes, means that class 'has a' another class internally. for ex : Consider a Customer class below

  public class Customer 
    {
       public Address HomeAddress { get; set; } //'Composition' or 'has a' Relation
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EMail { get; set; }
        ...........

    }

Note : (Assume that Address class is another class which contain properties like AddLine1,AddLine2,City,State etc.)

Now Once you initialize the object of Customer class all properties of that class will initialize with it's default values, below will be the default values of object of the above class

    HomeAddress = null
    FirstName = null
    LastName = null
    EMail = null

so this can lead to run time exception as in your case where you have just declared 'Errors' property but didn't initialized it , And in order to use it you should initialize it,using constructor like below :

public Customer 
{
HomeAddress  = new Address();
FirstName  = "";
LastName  = "";
EMail = "";
}

so similarly you can initialize 'Errors' property in class constructor

1 Comment

Thanks a lot, your explanation is awesome!

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.