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?